C#
Built-in attributes
Learn attributes like [Obsolete], [Conditional] and [Serializable].
Built-in attributes
C# ships several common built-in attributes. [Obsolete] marks an element as deprecated and the compiler emits a warning or error. [Conditional("DEBUG")] makes calls to a method compile only when the relevant symbol is defined.
[Serializable] declares that a type can be serialized; it is read by legacy serialization APIs. These are common attributes that steer compiler and runtime behavior without custom code.
[Conditional] details
[Conditional("DEBUG")] marks a method; calls to it compile only when DEBUG is defined. The method itself is always compiled; only the call sites are affected. This is common in logging and diagnostic code.
The Conditional attribute applies only to void-returning methods. Multiple symbols are allowed: [Conditional("DEBUG"), Conditional("TRACE")]. The condition is evaluated at compile time; there is no runtime cost.
Exercise Apply Obsolete and print Message
Apply [Obsolete("Use NewMethod")] to OldMethod in the Tool class below. In Main, read it with Attribute.GetCustomAttribute(typeof(Tool).GetMethod("OldMethod"), typeof(ObsoleteAttribute)) as ObsoleteAttribute and print attr.Message with Console.WriteLine.
Show example solution
var attr = Attribute.GetCustomAttribute(typeof(Tool).GetMethod("OldMethod"), typeof(ObsoleteAttribute)) as ObsoleteAttribute; Console.WriteLine(attr.Message);
Example solution:
using System;
class Tool
{
[Obsolete("Use NewMethod")]
public static void OldMethod() { }
}
class Program
{
static void Main()
{
var attr = Attribute.GetCustomAttribute(typeof(Tool).GetMethod("OldMethod"), typeof(ObsoleteAttribute)) as ObsoleteAttribute;
Console.WriteLine(attr.Message);
}
}
Test yourself
-
Complete the Obsolete attribute
[____]
void Old() { }
Show answer
[Obsolete]
void Old() { }
-
What does [Conditional("DEBUG")] do?
- Always removes the method
- Compiles the method only in DEBUG
- Keeps the call if DEBUG is defined, otherwise removes it
- Makes the method async
Show answer
Keeps the call if DEBUG is defined, otherwise removes it — Correct. Conditional keeps or removes the call based on the symbol; the method itself always compiles.
-
Match the attribute to its purpose
- [Obsolete]
- Marks as deprecated
- [Conditional]
- Keeps call conditional
- [Serializable]
- Marks as serializable
- [AttributeUsage]
- Restricts targets
Next lesson: Summary - Attributes