How to work with reflection in C#

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

Reflection

Reflection

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.

This article is published as part of the IDG Contributor Network. Want to Join?

To comment on this article and other InfoWorld content, visit InfoWorld's LinkedIn page, Facebook page and Twitter stream.
From CIO: 8 Free Online Courses to Grow Your Tech Skills
Notice to our Readers
We're now using social media to take your comments and feedback. Learn more about this here.