About
In this code snippet, we will take a look at reflection in C#.
Reflection is used to get metadata(information) about an object at runtime. We can get members(properties, methods) of objects and their data types. Reflection is also used for late binding. The ability to see the metadata of an object is for example, useful is when you use generics, as you don’t necessarily know the data type of a generic member until the object is created.
Let’s look at the code example below to see how reflection is used.
Code:
using System; //Add this. using System.Reflection; namespace Reflection { class Program { static void Main(string[] args) { //Specify namespace.class and get back a Type object that contains all the info about namespace.class. Type T = Type.GetType("Reflection.MyClass"); //Or ... Type T2 = typeof(MyClass); //Get methods, classes, properties, ... and save them in an array. PropertyInfo[] properties = T.GetProperties(); MethodInfo[] methods = T.GetMethods(); //Iterate through array and write out the attributes of your methods, classes, properties, .... foreach (var property in properties) { Console.WriteLine("Full property: "+property+", Name: "+property.Name + ", Type: " + property.PropertyType.Name); } foreach (var method in methods) { Console.WriteLine("Full Method: " + method + ", Name: " + method.Name + ", Type: " + method.ReturnType.Name); } Console.ReadLine(); } } class MyClass { public int MyFirstProperty { get; set; } public int MySecondProperty { get; set; } public string MyThirdProperty { get; set; } public void MyMethod() { Console.WriteLine("MyMethod did this."); } public void MySecondMethod() { Console.WriteLine("MySecondMethod did this."); } } }