Reflection in C#.NET with example

Hey friends..! Welcome to my another blog post on Reflection in C#.NET. One of my friend from Mumbai "Khadak Bist - Technical Consultant at Questpond" asked me to write an article on reflection because he says this question is frequently asked in interviews and this will be helpful for individuals preparing interviews. So this gave me the great chance to write a blog post on c# reflection. So like "Khadak Bist" if you guys know more about frequently asked or mostly asked interview questions, kindly post it in the below comment section. This may help others to prepare interviews and as well as helpful for onlinebuff to post more articles on your posted questions because this blog purely meant to help individuals in preparing interviews.

What is a Reflection

In simple words : Reflection is used when you want to inspect / determine / modify contents of an assembly.

Reflection is used get the metadata information of an assembly. Metadata (data about data) information means information about methods, properties, variables declared inside of an assembly not only it helps to retrieve information but also using reflection objects we can modify the type information and type behavior of an assembly at runtime.

In order to use reflection in an application, import or reference System.Reflection namespace using "using" keyword.

Assembly : DLL file of a class library or DLL of an application.

We can use reflection to dynamically create an instance of a type object (From assembly) or to invoke its methods, fields and properties or set/bind values to its methods and properties at runtime.

 
using System.Reflection;

One of the biggest implementation of a reflection you can find it in visual studio IDE developed by Microsoft Team. In a visual studio when you create any variable object let's say "string" type variable object.

When you use that string type variable object followed by (.) [DOT]. The moment you click on the "dot" visual studio automatically shows up an intellisense with all methods/functions and properties related to that class "String" and this technique of intellisense is possible because of reflection used by Microsoft Team.

Sample Example
 

using System;
using System.Reflection;

namespace ConsoleReflection
{
    class Program
    {
        static void Main(string[] args)
        {
            string _name;
        }
    }
}

Above code just to demonstrate the use of reflection in visual studio IDE. If you take "_name" object of a string then click on DOT (.). The moment you click on DOT (.) it will throw all methods/functions and properties related to that class "String" as shown in below image snapshot.

So from above example it is been concluded that reflection actually goes inside and inspects metadata of an assembly.

I hope you are now familiar with the concept of reflection in c#. If you still have any doubts or if i was missed anything kindly let me know throught your comments.

Step by step Create Reflection

Creating reflection is a 3 step process let's do one by one.

Step 1 : Import Reflection Namespace

Before you start coding your application you need to import the reflection namespace from system an example is shown below.

 
using System.Reflection;

Step 2 : Load the DLL or assembly File

Once you have imported the reflection namespace, its time to load the dll file or assembly file in order to get reference of an assembly why because we need to get type of object, oce we have that type of object then using that object we can get the metadata of an assembly as sample shown in below snippet of code.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ConsoleReflection
{
    class Program
    {
        static void Main(string[] args)
        {
            Assembly myAssembly = Assembly.LoadFile(@"D:\Reflection\ConsoleReflection\reflection.dll");

            //Get type of object from loaded assembly



   
        }
    }
}

So as you see from above code that we have successfully referenced an assembly file in our console application main program using language c# (c-sharp).

After referencing an assembly, now its time to get type of object or class reference from loaded assembly.

 

    class Program
    {
        static void Main(string[] args)
        {
            Assembly myAssembly = Assembly.LoadFile(@"D:\Reflection\ConsoleReflection\reflection.dll");

            //Get type of object from loaded assembly

            Type myType = myAssembly.GetType("TestReflection.clsReflection");

   
        }
    }

So as see from above code that by using an assembly object "myAssembly" we are invoking the class reference as shown below.

 
   Type myType = myAssembly.GetType("TestReflection.clsReflection");

Step 3 : Create Instance of Class From Assembly

So we have class reference which we have loaded from an assembly. Now let's create instance of a class.

 

class Program
    {
        static void Main(string[] args)
        {
            Assembly myAssembly = Assembly.LoadFile(@"D:\Reflection\ConsoleReflection\reflection.dll");

            //Get type of object from loaded assembly

            Type myType = myAssembly.GetType("TestReflection.clsReflection");

            object objInstance = Activator.CreateInstance(myType);
   
        }
    }

As you see from above code that we have created an instance of a class using "Activator.CreateInstance". why we have used "Activator.CreateInstance" is because my assembly "reference.dll" is currently not referenced directly in my console application but it is referenced in my console application via reflection. So "Activator.CreateInstance" is important method to create reference of a class which is loaded from an assembly.

So after creating the class object rest is very simple just we need to get the class type using "GetType()" method as shown below.

 

 class Program
 {
        static void Main(string[] args)
        {
            Assembly myAssembly = Assembly.LoadFile(@"D:\Reflection\ConsoleReflection\reflection.dll");

            //Get type of object from loaded assembly

            Type myType = myAssembly.GetType("TestReflection.clsReflection");

            object objInstance = Activator.CreateInstance(myType);

            Type objectType = objInstance.GetType();

   
        }
  }

So rest is simple you can do any thing using this "objectType" and "objInstance" either you can invoke methods, properties and variables or you bind values to methods or properties.

I hope you have understood the practical demo to create a reflection and how to dynamically load an assembly and invoke assembly methods, properties, variables now let do a small code example using reflection.

Reflection Example in C-Sharp.Net

In this we will create a console application and to application we will add new class library. So let's start with the console application.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ConsoleReflection
{
    class Program
    {
        static void Main(string[] args)
        {
           
   
        }
    }
}

Next step to add up a new class library to the application.

As you see from above the image we have successfully added the class library in the console application project.

Let's do some coding in class library

 

public class clsCalculation
{

        private int _num1 = 0;
        private int _num2 = 0;

        public void ClearResults()
        {
            _num1 = 0;
            _num2 = 0;
        }

        public int SetNum1
        {
            set
            {
                _num1 = value;
            }
            get
            {
                return _num1;
            }
        }

        public double Sum(int a, int b)
        {
            _num1 = a;
            _num2 = b;

            return _num1 + _num2;

        }

        public double Sub(int a, int b)
        {
            _num1 = a;
            _num2 = b;

            return _num1 - _num2;

        }


        public double Mul(int a, int b)
        {
            _num1 = a;
            _num2 = b;

            return _num1 * _num2;

        }

        public double Div(int a, int b)
        {
            _num1 = a;
            _num2 = b;

            return _num1 / _num2;

        }

        public double AreaofCircle(int radius)
        {
           double value1 = Math.Pow(radius, 2);
           return 3.14 * value1;

        }


        public double AreaofTriangle(int _base, int _height)
        {
            _num1 = _base;
            _num2 = _height;

            return _num1 * _num2;

        }


        public double AreaofSphere(int radius)
        {
            double value1 = Math.Pow(radius, 2);
            return 4* 3.14 * value1;

        }

        public double VolumeaofSphere(int radius)
        {
            double value1 = Math.Pow(radius, 2);
            return (4 / 3) * (3.14 * value1);

        }


        public void PrintClassName()
        {

            Console.WriteLine("clsCalculation...Printing");

        }




    }

As you from code we have created a simple class called "clsCalculation" with methods, properties and variables then let's click on F6 button to compile the class library. When we compiled the code DLL or an assembly file is been created in the class library Bin folder.

Now let's dynamically load an assembly in our main application program.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ConsoleReflection
{
    class Program
    {
        static void Main(string[] args)
        {

            Assembly myAssembly = Assembly.LoadFile(@"D:\Reflection\ConsoleReflection\ClassLibrary1\bin\Debug\ClassLibrary1.dll");

            //Get type of object from loaded assembly

            Type myType = myAssembly.GetType("ClassLibrary1.clsCalculation");

            object objInstance = Activator.CreateInstance(myType);

            Type objectType = objInstance.GetType();

   
        }
    }
}

As you see we have successfully dynamically loaded our classLibrary assembly in our main program via reflection.

Now let's display all classLibrary members using reflection.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ConsoleReflection
{
    class Program
    {
        static void Main(string[] args)
        {

            Assembly myAssembly = Assembly.LoadFile(@"D:\Reflection\ConsoleReflection\ClassLibrary1\bin\Debug\ClassLibrary1.dll");

            //Get type of object from loaded assembly

            Type myType = myAssembly.GetType("ClassLibrary1.clsCalculation");

            object objInstance = Activator.CreateInstance(myType);

            Type objectType = objInstance.GetType();


            foreach(MemberInfo objMemberInfo in objectType.GetMembers()){

                Console.WriteLine(objMemberInfo.Name);

            }
   
        }
    }
}

Display Output

So as you see friends we have able to read metadata of an assembly via reflection.

Invoke Particular Method via Reflection

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ConsoleReflection
{
    class Program
    {
        static void Main(string[] args)
        {

            Assembly myAssembly = Assembly.LoadFile(@"D:\Reflection\ConsoleReflection\ClassLibrary1\bin\Debug\ClassLibrary1.dll");

            //Get type of object from loaded assembly

            Type myType = myAssembly.GetType("ClassLibrary1.clsCalculation");

            object objInstance = Activator.CreateInstance(myType);

            Type objectTypes = objInstance.GetType();

            objectTypes.InvokeMember("PrintClassName", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod | BindingFlags.Instance, null, objInstance, null);
   
        }
    }
}

Display Output

Invoke Particular Method with input values via Reflection

 

            double answer = (double)objectTypes.InvokeMember("Sum", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod | BindingFlags.Instance, null, objInstance, new object[] { 20,10 });

            Console.WriteLine(answer);
      

Display Output

30

As you see to bind values to a method via "InvokeMember" function we need to just change the last parameter as shown in above code.

SET Value to a Property

 
 PropertyInfo numberPropertyInfo = objectTypes.GetProperty("SetNum1");
 numberPropertyInfo.SetValue(objInstance, 10, null);

Get Value of a Property

 
PropertyInfo numberPropertyInfo = objectTypes.GetProperty("SetNum1");
int value = (int)numberPropertyInfo.GetValue(objInstance, null);

Benefits of using reflection

To read assembly metadata.

To invoke assembly reference on a runtime.

If you are developing IDE's like visual studio then to display members of a class you can use Reflection.

You can use reflection any where, where you want to dynamically display all members of DLL.

So hey friends this is all about the reflection in c#. If you have more doubts or queries please feel free to drop your comment in the below comment section.

If you like this article then share it with your friends on Google+, Facebook and Twitter.

Author: Gurunatha Dogi

Gurunatha Dogi

Gurunatha Dogi is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server and lots more..... read more

Add a Comment