Understanding Reflection in C#: A Comprehensive Guide
Written on
Chapter 1: Introduction to Reflection
Reflection is a technique that allows developers to inspect and manipulate a program’s structure and behavior during its execution. With Reflection, it’s possible to dynamically identify types, methods, properties, constructors, and other members of a program without prior knowledge at compile time. This powerful feature enables flexible interactions with types and objects, and can also retrieve information about events defined within a type, including their names, handlers, and metadata.
Section 1.1: Common Applications of Reflection
Reflection serves several important functions in C#. Here are a few common applications:
- Type Inspection: You can use Reflection to gather information about types at runtime, including their properties, methods, fields, and attributes.
- Dynamic Instance Creation: Reflection allows you to create instances of types at runtime, even if you only know the type’s name during execution.
- Method and Property Invocation: You can invoke methods and access properties at runtime, which is particularly useful when member names are unknown at compile time.
- Field Access and Modification: Reflection facilitates the retrieval and modification of object fields at runtime.
- Attribute Inspection: You can examine the attributes applied to various program elements (types, fields, methods, properties, constructors) and take actions based on this information.
Subsection 1.1.1: Example of Reflection in C#
using System;
using System.Reflection;
public class FruitClass
{
public string FruitName { get; set; }
public void DisplayFruitName()
{
Console.WriteLine("Name of Fruit is: " + FruitName);}
}
class Program
{
public static void Main(string[] args)
{
// Dynamically obtain assembly information
Type stringType = typeof(System.String);
Console.WriteLine(stringType.Assembly);
Console.WriteLine(stringType.FullName);
// Dynamically create an instance of FruitClass
Type fruitType = typeof(FruitClass);
object fruitInstance = Activator.CreateInstance(fruitType);
// Access and set a property dynamically
PropertyInfo propertyInfo = fruitType.GetProperty("FruitName");
propertyInfo.SetValue(fruitInstance, "Mango, Reflection");
// Invoke a method dynamically
MethodInfo methodInfo = fruitType.GetMethod("DisplayFruitName");
methodInfo.Invoke(fruitInstance, null);
// Retrieve the property value
string propertyValue = (string)propertyInfo.GetValue(fruitInstance);
Console.WriteLine("Property value: " + propertyValue);
}
}
Section 1.2: Using Reflection with Events
Reflection can also be used to work with events in C#. Below is an example demonstrating how to retrieve event information dynamically.
using System;
using System.Reflection;
public class EventExample
{
public event EventHandler FruitEvent;
public void TriggerEvent()
{
// Raise the event
FruitEvent?.Invoke(this, EventArgs.Empty);
}
}
class Program
{
public static void Main(string[] args)
{
// Instantiate the EventExample class
EventExample example = new EventExample();
// Get the type of the instance
Type type = example.GetType();
// Retrieve and display event information
EventInfo[] events = type.GetEvents();
foreach (EventInfo evt in events)
{
Console.WriteLine($"Event Name: {evt.Name}");
Console.WriteLine($"Event Handler Type: {evt.EventHandlerType}");
}
}
}
Chapter 2: Exploring Enums with Reflection
Enums can also be inspected using Reflection. The following example illustrates how to retrieve details about an enum type.
using System;
using System.Reflection;
public enum FruitEnum
{
Apple,
Banana,
Mango,
Grape,
Orange,
Cherry,
Kiwi
}
class Program
{
public static void Main(string[] args)
{
// Dynamically obtain enum type information
Type enumType = typeof(FruitEnum);
Console.WriteLine($"Enum Name: {enumType.Name}");
// Display enum values
Array enumValues = Enum.GetValues(enumType);
foreach (object value in enumValues)
{
Console.WriteLine($"Name: {Enum.GetName(enumType, value)}, Value: {value}");}
}
}
Thanks for reading! For more insightful tutorials, please visit C-Sharp Tutorial. If you found this article helpful, consider supporting the author by clicking the button below.