0
0
C Sharp (C#)programming

Attribute declaration syntax in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an attribute in C#?
An attribute in C# is a way to add metadata to your code, like extra information about classes, methods, or properties that can be used by the compiler or runtime.
Click to reveal answer
beginner
How do you declare an attribute in C#?
You declare an attribute by creating a class that inherits from System.Attribute and usually ends with the word 'Attribute'.
Click to reveal answer
beginner
What is the syntax to apply an attribute to a class or method?
You place the attribute name in square brackets above the class or method. For example: <br><pre>[Serializable]<br>public class MyClass { }</pre>
Click to reveal answer
intermediate
Can attribute names be shortened when applied? How?
Yes. When applying an attribute, you can omit the 'Attribute' suffix. For example, [Serializable] is short for [SerializableAttribute].
Click to reveal answer
intermediate
How do you pass parameters to an attribute?
You pass parameters inside parentheses after the attribute name, like a method call. For example: <br>
[Obsolete("Use new method instead")]
public void OldMethod() { }
Click to reveal answer
Which base class must a custom attribute class inherit from in C#?
ASystem.Class
BSystem.Attribute
CSystem.Metadata
DSystem.Object
How do you apply an attribute named 'TestAttribute' to a method named 'Run'?
ABoth B and C are correct
B[TestAttribute] public void Run() { }
C[Test] public void Run() { }
DYou cannot apply attributes to methods
What symbol is used to declare an attribute above a class or method?
A{}
B()
C[]
D<>
How do you pass a string parameter 'Hello' to an attribute named 'Example'?
A[Example: "Hello"]
B[Example('Hello')]
C[Example = "Hello"]
D[Example("Hello")]
Which of these is a valid attribute class declaration?
Apublic class MyAttr : System.Attribute { }
Bpublic class MyAttr { }
Cpublic attribute MyAttr { }
Dpublic class MyAttr : AttributeBase { }
Explain how to declare and apply a custom attribute in C#.
Think about how you add extra info to classes or methods.
You got /4 concepts.
    Describe how to pass parameters to an attribute and why it might be useful.
    Consider how you give extra details to the attribute.
    You got /4 concepts.