C# Reflection


C# Reflection is a powerful feature that allows you to inspect and manipulate types, methods, properties, and fields at runtime. It enables you to dynamically create instances of types, bind to existing objects, and access metadata about assemblies and types.


The System.Reflection namespace in C# provides a rich set of classes that allow developers to inspect metadata about types, methods, properties, and more at runtime. This capability is essential for scenarios where you need to work with types dynamically, such as in frameworks, libraries, or applications that require extensibility and flexibility.

Key Classes in the System.Reflection Namespace

Here are some of the key classes and their purposes within the System.Reflection namespace:

  1. Assembly: Represents a compiled code library used by .NET applications. It contains metadata about the assembly itself, including its version, culture, and public key.

  2. Type: Represents type declarations (classes, interfaces, arrays, etc.) and provides methods to obtain information about the members of the type (methods, properties, fields, etc.).

  3. MethodInfo: Provides information about a method, including its name, return type, parameters, and attributes. It also allows you to invoke the method dynamically.

  4. PropertyInfo: Provides information about a property, including its name, type, and accessors (getters and setters). It allows you to get or set property values dynamically.

  5. FieldInfo: Provides information about a field, including its name and type. It allows you to get or set field values dynamically.

  6. ConstructorInfo: Provides information about a constructor and allows you to create instances of a type dynamically.

  7. ParameterInfo: Provides information about the parameters of a method or constructor.

Here are some key concepts and examples of how reflection can be used in C#:

Key Concepts of C# Reflection

  • Metadata: Reflection provides access to metadata about assemblies, modules, and types. This includes information such as type definitions, method signatures, and property attributes.

  • Dynamic Type Creation: You can create instances of types at runtime without knowing their names at compile time.

  • Late Binding: Reflection allows you to invoke methods and access properties dynamically, which is useful when the types are not known until runtime.

  • Performance Considerations: While reflection is powerful, it can be slower than direct method calls due to the overhead of inspecting types and invoking members dynamically.

Applications of Reflection

  1. Viewing Attribute Information at Runtime:
    Enables inspection of custom attributes applied to classes, methods, properties, and other members at runtime.

  2. Examining Types in an Assembly and Instantiating Them:
    Allows exploration of all types defined in an assembly and the creation of instances of those types dynamically.

  3. Late Binding to Methods and Properties:
    Facilitates the dynamic invocation of methods and access to properties when the types are not known until runtime.

  4. Creating New Types at Runtime:
    Permits the definition and creation of new types dynamically, enabling tasks such as code generation and dynamic proxies.

Example 1: Basic Reflection Usage

This example demonstrates how to use reflection to obtain information about the string type.

csharp
1// C# program to illustrate 2// the use of Reflection 3using System; 4using System.Reflection; 5 6namespace Reflection_Demo { 7 class Program { 8 static void Main(string[] args) { 9 Type t = typeof(string); 10 Console.WriteLine("Name : {0}", t.Name); 11 Console.WriteLine("Full Name : {0}", t.FullName); 12 Console.WriteLine("Namespace : {0}", t.Namespace); 13 Console.WriteLine("Base Type : {0}", t.BaseType); 14 } 15 } 16}

Output:

1Name : String 2Full Name : System.String 3Namespace : System 4Base Type : System.Object

Example 2: Accessing Assembly Metadata

In this example, we load an assembly and inspect its types, methods, and properties.

csharp
1// C# program to illustrate 2// the use of Reflection 3using System; 4using System.Linq; 5using System.Reflection; 6 7namespace SimpliReflectionDemo { 8 class Program { 9 static void Main(string[] args) { 10 var assembly = Assembly.LoadFrom(@"C:\Path\To\Your\Assembly.dll"); 11 foreach (var type in assembly.GetTypes()) { 12 Console.WriteLine($"Type: {type.Name}"); 13 Console.WriteLine("============================="); 14 var instance = Activator.CreateInstance(type); 15 foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance)) { 16 Console.WriteLine($"Method: {method.Name}"); 17 method.Invoke(instance, null); 18 } 19 Console.WriteLine("============================="); 20 } 21 } 22 } 23}

Example 3: Creating Instances Dynamically

This example shows how to create an instance of a class and access its properties and methods.

csharp
1// C# program to illustrate 2// creating instances using Reflection 3using System; 4using System.Reflection; 5 6namespace ReflectionExample { 7 public class Calculator { 8 public double Add(double a, double b) { 9 return a + b; 10 } 11 } 12 13 class Program { 14 static void Main(string[] args) { 15 Type calcType = typeof(Calculator); 16 object calcInstance = Activator.CreateInstance(calcType); 17 MethodInfo addMethod = calcType.GetMethod("Add"); 18 double result = (double)addMethod.Invoke(calcInstance, new object[] { 5, 10 }); 19 Console.WriteLine($"Result of Add: {result}"); 20 } 21 } 22}

Output:

1Result of Add: 15

Example 4: Accessing Properties and Fields

This example demonstrates how to access and modify properties and fields of a class using reflection.

csharp
1// C# program to illustrate 2// accessing properties and fields 3using System; 4using System.Reflection; 5 6namespace ReflectionDemo { 7 public class Person { 8 private string name; 9 public string Name { 10 get { return name; } 11 set { name = value; } 12 } 13 } 14 15 class Program { 16 static void Main(string[] args) { 17 Type personType = typeof(Person); 18 object personInstance = Activator.CreateInstance(personType); 19 PropertyInfo nameProperty = personType.GetProperty("Name"); 20 nameProperty.SetValue(personInstance, "John Doe"); 21 Console.WriteLine($"Person's Name: {nameProperty.GetValue(personInstance)}"); 22 } 23 } 24}

Output:

1Person's Name: John Doe

Talk to us?

Post your blog