Attribute basics
Learn to add metadata with [Attribute].
What is an attribute?
An attribute adds metadata to code that can be read at compile time or runtime. It is written in square brackets before an element such as a class, method or property: [Serializable] class Sample { }.
Attributes do not change behavior directly; the compiler, runtime and reflection read them to decide behavior. For example [Serializable] marks a class as serializable; [Obsolete] marks a method as deprecated.
Attribute syntax
Attributes are written in square brackets before the target element. Example: [Obsolete("Use NewMethod")] void OldMethod() { }. Here Obsolete is the attribute name and "Use NewMethod" is a constructor argument.
The attribute class name ends with Attribute (e.g. ObsoleteAttribute); but you can omit the suffix when applying. Multiple attributes are comma-separated or on separate lines. Some take parameters, some don't.
Exercise Apply Serializable and check
Add the [Serializable] attribute to the Sample class below. In Main, get the type with Type t = typeof(Sample); and print the result with Console.WriteLine(t.IsSerializable);.
Show example solution
Write [Serializable] above the Sample class. In Main add Type t = typeof(Sample); and Console.WriteLine(t.IsSerializable);.
Example solution:
using System;
[Serializable]
class Sample { }
class Program
{
static void Main()
{
Type t = typeof(Sample);
Console.WriteLine(t.IsSerializable);
}
}
Test yourself
-
What does an attribute do?
- Runs code faster
- Hides a method
- Adds metadata to code
- Makes a variable constant
Show answer
Adds metadata to code — Correct. An attribute adds metadata to code and can be read via reflection.
-
Complete the attribute usage
[____] class MyClass { }Show answer
[Serializable] class MyClass { } -
Match the attribute to its target
- [Serializable]
- Class
- [Obsolete]
- Deprecated method
- [Conditional]
- Conditional method
- [XmlAttribute]
- Property