Advanced C# Features: Attributes
Quick Answer
Attributes in C# provide a powerful way to add metadata to your code elements such as classes, methods, and properties. They enable declarative programming by allowing you to specify additional information that can be inspected at runtime or compile time to influence behavior or tooling.
Learning Objectives
- Explain the purpose of Attributes in a practical learning context.
- Identify the main ideas, terms, and decisions involved in Attributes.
- Apply Attributes in a simple real-world scenario or practice task.
Introduction to Attributes in C#
Attributes in C# are a way to add declarative information to your code elements such as classes, methods, properties, and more.
This metadata can be used by the runtime or tools to modify behavior, enforce rules, or provide additional information without changing the core logic.
Attributes provide a powerful way to add metadata to your code.
What Are Attributes?
Attributes are classes that inherit from System.Attribute and can be applied to various program elements.
They allow you to attach declarative information that can be queried at runtime using reflection.
- Can be applied to classes, methods, properties, assemblies, and more.
- Provide metadata that does not affect program logic directly.
- Can influence runtime behavior or tooling.
Using Built-in Attributes
C# provides many built-in attributes such as [Obsolete], [Serializable], and [DllImport].
These attributes serve common purposes like marking deprecated code or enabling serialization.
- [Obsolete] marks code as deprecated and can generate compiler warnings or errors.
- [Serializable] indicates a class can be serialized.
- [DllImport] is used for interop with unmanaged code.
Creating Custom Attributes
You can define your own attributes by creating classes derived from System.Attribute.
Custom attributes can have positional and named parameters to store metadata.
- Define a class inheriting from System.Attribute.
- Use constructors for positional parameters.
- Use public properties for named parameters.
- Apply the attribute using square brackets.
Example: Defining a Custom Attribute
Here is an example of a custom attribute that stores a version number.
Retrieving Attributes via Reflection
To access attribute data at runtime, use reflection to inspect the attributes applied to code elements.
This allows dynamic behavior based on metadata.
- Use methods like GetCustomAttributes to retrieve attributes.
- Check for attribute presence and read its properties.
- Commonly used in frameworks and libraries.
Attribute Usage and Targets
You can control where an attribute can be applied using the AttributeUsage attribute.
This restricts usage to classes, methods, properties, assemblies, etc.
- Specify valid targets with AttributeTargets enum.
- Control whether multiple instances are allowed.
- Control inheritance of attributes.
Practical Example
This example defines a custom attribute 'VersionAttribute' with a positional parameter. It is applied to a class and a method to specify version information.
This example uses reflection to retrieve and print the version information from the custom attributes applied to the class and method.
Examples
using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class VersionAttribute : Attribute
{
public string Number { get; }
public VersionAttribute(string number)
{
Number = number;
}
}
[Version("1.0.0")]
public class SampleClass
{
[Version("1.0.1")]
public void SampleMethod() { }
}This example defines a custom attribute 'VersionAttribute' with a positional parameter. It is applied to a class and a method to specify version information.
using System;
using System.Reflection;
class Program
{
static void Main()
{
Type type = typeof(SampleClass);
var classAttributes = type.GetCustomAttributes(typeof(VersionAttribute), false);
foreach (VersionAttribute attr in classAttributes)
{
Console.WriteLine($"Class Version: {attr.Number}");
}
MethodInfo method = type.GetMethod("SampleMethod");
var methodAttributes = method.GetCustomAttributes(typeof(VersionAttribute), false);
foreach (VersionAttribute attr in methodAttributes)
{
Console.WriteLine($"Method Version: {attr.Number}");
}
}
}This example uses reflection to retrieve and print the version information from the custom attributes applied to the class and method.
Best Practices
- Use attributes to separate metadata from business logic.
- Keep attribute parameters simple and meaningful.
- Use AttributeUsage to restrict attribute application appropriately.
- Avoid overusing attributes to prevent clutter and confusion.
- Document custom attributes clearly for maintainability.
Common Mistakes
- Applying attributes to unsupported targets without AttributeUsage.
- Using attributes for logic that should be handled by code instead of metadata.
- Not retrieving attributes correctly via reflection.
- Defining attributes without meaningful parameters.
- Ignoring performance implications of excessive reflection.
Hands-on Exercise
Create a Custom Author Attribute
Define a custom attribute named 'AuthorAttribute' that stores the author's name and version. Apply it to a class and retrieve the information using reflection.
Expected output: Console output showing the author's name and version from the attribute.
Hint: Inherit from System.Attribute and use AttributeUsage to restrict to classes.
Use Built-in Obsolete Attribute
Mark a method as obsolete using the [Obsolete] attribute and observe compiler warnings when calling it.
Expected output: Compiler warning or error indicating the method is obsolete.
Hint: Use [Obsolete("message", true)] to generate an error instead of a warning.
Interview Questions
What is the purpose of attributes in C#?
InterviewAttributes provide a way to add declarative metadata to code elements, which can be inspected at runtime or compile time to influence behavior or tooling.
How do you create a custom attribute in C#?
InterviewBy defining a class that inherits from System.Attribute and optionally using constructors and properties to define parameters.
How can you retrieve attribute information at runtime?
InterviewUsing reflection methods like GetCustomAttributes on types, methods, or other members to access applied attributes.
MCQ Quiz
1. What is the best first step when learning Attributes?
A. Understand the purpose and basic idea
B. Skip directly to advanced implementation
C. Ignore examples and practice
D. Memorize terms without context
Correct answer: A
Starting with the purpose and basic idea makes later examples and practice easier to understand.
2. Which activity helps reinforce Attributes?
A. Reading once without practice
B. Building or writing a small practical example
C. Avoiding review questions
D. Skipping the summary
Correct answer: B
A small practical example helps connect the topic to real usage.
3. Which statement is most accurate about this topic?
A. Attributes in C# provide a powerful way to add metadata to your code elements such as classes, methods, and properties.
B. Attributes never needs examples
C. Attributes is unrelated to practical work
D. Attributes should be learned without checking results
Correct answer: A
The correct option is based on the available topic explanation.
Key Takeaways
- Attributes in C# provide a powerful way to add metadata to your code elements such as classes, methods, and properties.
- They enable declarative programming by allowing you to specify additional information that can be inspected at runtime or compile time to influence behavior or tooling.
- Attributes in C# are a way to add declarative information to your code elements such as classes, methods, properties, and more.
- This metadata can be used by the runtime or tools to modify behavior, enforce rules, or provide additional information without changing the core logic.
- Attributes are classes that inherit from System.Attribute and can be applied to various program elements.
Summary
Attributes in C# are a powerful feature to add metadata to your code elements.
They enable declarative programming and can influence runtime behavior or tooling.
You can use built-in attributes or create custom ones tailored to your needs.
Reflection allows you to retrieve and act on attribute data dynamically.
Proper use of attributes improves code clarity, maintainability, and flexibility.
Frequently Asked Questions
Can attributes change program logic directly?
No, attributes themselves do not change program logic but provide metadata that can be used by tools or runtime to influence behavior.
What is AttributeUsage in C#?
AttributeUsage is an attribute that specifies the valid targets, inheritance, and multiplicity rules for a custom attribute.
Are attributes inherited by derived classes?
By default, attributes are not inherited unless the AttributeUsage attribute specifies Inherited = true.
What is Attributes?
Attributes in C# provide a powerful way to add metadata to your code elements such as classes, methods, and properties.
Why is Attributes important?
They enable declarative programming by allowing you to specify additional information that can be inspected at runtime or compile time to influence behavior or tooling.
How should I practice Attributes?
Attributes in C# are a way to add declarative information to your code elements such as classes, methods, properties, and more.

