Joydip Kanjilal
Contributor

How to work with reflection in C#

opinion
Jan 29, 20164 mins
Software Development

Take advantage of reflection in .Net to inspect or retrieve metadata of a type at runtime

Reflection in C# is used to retrieve metadata on types at runtime. In other words, you can use reflection to inspect metadata of the types in your program dynamically — you can retrieve information on the loaded assemblies and the types defined in them. Reflection in C# is similar to RTTI (Runtime Type Information) of C++.

To work with reflection in .Net, you should include the System.Reflection namespace in your program. In using reflection, you get objects of the type “Type” that can be used to represent assemblies, types, or modules. You can use reflection to create an instance of a type dynamically and even invoke methods of the type.

The types defined in the System.Reflection namespace include the following.

  • Assembly
  • Module
  • Enum
  • MethodInfo
  • ConstructorInfo
  • MemberInfo
  • ParameterInfo
  • Type
  • FieldInfo
  • EventInfo
  • PropertyInfo

Let’s now dig into some code to put reflection into action. Consider the following class called Customer.

public class Customer

    {

        public int Id

        {

            get; set;

        }

        public string FirstName

        {

            get; set;

        }

        public string LastName

        {

            get; set;

        }

        public string Address

        {

            get; set;

        }

    }

The following code snippet shows how you can get the class name and the namespace name of the Customer class using reflection:

Type type = typeof(Customer);

Console.WriteLine("Class: " + type.Name);

Console.WriteLine("Namespace: " + type.Namespace);

The following code snippet illustrates how you can retrieve the list of the properties of the Customer class and display their names in the console window:

static void Main(string[] args)

        {

            Type type = typeof(Customer);

            PropertyInfo[] propertyInfo = type.GetProperties();

            Console.WriteLine("The list of properties of the Customer class are:--");

            foreach (PropertyInfo pInfo in propertyInfo)

            {

                Console.WriteLine(pInfo.Name);

            }

        }

The GetProperties() method of the Type class returns an array of type PropertyInfo – this is actually a list of the public properties of your type. You can then iterate this array and retrieve the names of each of the public properties defined in your type. Since the Customer class defines three properties, the names of all of these three properties would be displayed in the console when this program is executed.

Here’s how we can display the metadata of the constructors and public methods of a type using reflection. Let’s revisit the Customer class we created earlier and incorporate two methods — a default constructor and a method called Validate that is used to validate the customer object passed to it as a parameter. This is what the modified version of the Customer class would look like.

public class Customer

    {

        public Customer()

        {

            //Default constructor

        }

        public int Id

        {

            get; set;

        }

        public string FirstName

        {

            get; set;

        }

        public string LastName

        {

            get; set;

        }

        public string Address

        {

            get; set;

        }

        public bool Validate(Customer customerObj)

        {

            //Code to validate the customer object

            return true;

        }

    }

The following code snippet can be used to display the names of all the constructors that belong to the Customer class. We have just one constructor in the Customer class — hence, just one would be listed.

Type type = typeof(Customer);           

ConstructorInfo[] constructorInfo = type.GetConstructors();

Console.WriteLine("The Customer class contains the following Constructors:--");

foreach (ConstructorInfo c in constructorInfo)

  {

     Console.WriteLine(c);

  }

Note that the GetConstructors() method of the Type class returns an array of type ConstructorInfo that contains the list of all the public constructors defined in the type that is being reflected.

OK; let’s now display the names of all the public methods of the Customer class — again, we just have one so the name of just one method would be displayed in the console when the program given next is executed. Here’s the code listing for your reference.

static void Main(string[] args)

 {

    Type type = typeof(Customer);

    MethodInfo[] methodInfo = type.GetMethods();

     Console.WriteLine("The methods of the Customer class are:--");

            foreach (MethodInfo temp in methodInfo)

            {

              Console.WriteLine(temp.Name);               

            }

            Console.Read();

        }

Note that you might get the names of a few additional methods (ToString, Equals, GetHashCode, GetType) displayed as well. These methods are inherited from the Object class – any class in .Net derives the Object class by default.

You can also iterate through the attributes of a method. If custom attributes have been defined for your methods, you can use the GetCustomAttributes method on the instance of the MethodInfo class to retrieve the attributes of the method. Here’s how you can achieve this.

foreach (MethodInfo temp in methodInfo)

 {

    foreach (Attribute attribute in temp.GetCustomAttributes(true))

     {

         //Write your usual code here

     }

  }

So, if you decorate your business objects using attributes in your application, you can take advantage of reflection to reflect on the type, retrieve the attributes of the methods of your type and then perform some action accordingly.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author