Attributes provide a powerful method of associating metadata, or declarative information, with code (assemblies, types, methods, properties, and so forth). After an attribute is associated with a program entity, the attribute can be queried at run time by using a technique called reflection.
Attributes are used by many tools and frameworks. NUnit uses attributes like [Test] and [TestFixture] that are used by the NUnit test runner.
ASP.NET MVC uses attributes like [Authorize]
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct)] //AttributeUsage: restrict usage
public class AuthorAttribute : System.Attribute
{
private string Name;
public double Version;
public AuthorAttribute(string name)
{
Name = name;
Version = 1.0;
}
}
Obsolete This attribute signals that code is obsolete and shouldn't be used anymore.
[Obsolete("Use ThisClass2 instead.")] or [Obsolete]
public class ThisClass
{ }
C# reflection refers to the ability of the C# programming language to inspect and manipulate its own metadata and behavior during runtime. With reflection, you can dynamically examine and interact with types, classes, properties, methods, and other members of a program, even if they were not known at compile time.
using System;
using System.Reflection;
public class MyClass
{
public void SayHello(string name)
{
Console.WriteLine($"Hello, {name}!");
}
public int Add(int a, int b)
{
return a + b;
}
}
class Program
{
static void Main(string[] args)
{
// Instantiate MyClass using reflection
Type myClassType = typeof(MyClass);
object myClassInstance = Activator.CreateInstance(myClassType);
// Invoke SayHello method dynamically
MethodInfo sayHelloMethod = myClassType.GetMethod("SayHello");
sayHelloMethod.Invoke(myClassInstance, new object[] { "John" });
// Invoke Add method dynamically
MethodInfo addMethod = myClassType.GetMethod("Add");
int result = (int)addMethod.Invoke(myClassInstance, new object[] { 5, 3 });
Console.WriteLine($"Result of addition: {result}");
}
}