What is reflection in C#

Reflection in C# is a powerful feature that allows you to inspect the metadata of types in your application at runtime. It enables you to dynamically create instances of types, bind to properties, methods, and events, and even invoke methods or access fields and properties without knowing their names at compile time. This is particularly useful for scenarios like plugin development, serialization, and dependency injection.

Example of Reflection in C#

using System; using System.Reflection; public class Example { public void SayHello() { Console.WriteLine("Hello, World!"); } } class Program { static void Main(string[] args) { // Creating an instance of Example class Type exampleType = typeof(Example); object exampleInstance = Activator.CreateInstance(exampleType); // Getting and invoking the SayHello method MethodInfo methodInfo = exampleType.GetMethod("SayHello"); methodInfo.Invoke(exampleInstance, null); } }

Reflection C# Metadata Runtime Dynamic Type Creation