Reflection Introduction c#

Reflection Introduction c#

Hi friends, we have explained Insert data into Database table using SQLBulkCopy class in C#as keyword C#, Import/Upload Excel file in asp.net with C#The Microsoft Jet database engine cannot open the file. It is already opened exclusively by another user,   Call method after specific time interval C#Alert from code behind asp.net,required field validator in asp.net,Difference between RegisterClientScriptBlock and RegisterStartupScript asp.netDifference between ref and out parameters.

Reflection is used to create dynamic objects of any type. It is used to bind type to an existing object,Invoke method at runtime,Access properties and parameters.

Reflection Introduction Example-1 :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReflectionExample
{
    public class ClsClasses
    {
        public string getstring()
        {
            return "Welcome, Sohil Raval !";
        }
        
    }
}

In above example there is a method. Now lets understand how to call these methods using Reflection.  First have a look into below example and will understand in details. Below example is to call first method “getstring”.

private string CallSimpleMethod()
{
    //Name of Assembly...
    string AssemblyName = "ReflectionExample";   
    //Classname with its NameSpace
    string NamespaceName = "ReflectionExample.ClsClasses";   
    var objClassInstance = System.Activator.CreateInstance(AssemblyName, NamespaceName).Unwrap();
    object objMethodResult = null;
    MethodInfo miMethod = null;
    Type tClsType = objClassInstance.GetType();
    MemberInfo[] mInfoMethods = tClsType.GetMember("getstring");
    if (mInfoMethods.Length == 1)
    {
        //Get method from respective class
        miMethod = tClsType.GetMethod(Convert.ToString("getstring"));  
    }
    else    //check Whether Method OverLoaded or not
    {
        List<Type> lstPrms = new List<Type>();
        //Get method from respective class
        miMethod = tClsType.GetMethod(Convert.ToString("getstring"), lstPrms.ToArray());  
    }
    //Invoke method
    objMethodResult = miMethod.Invoke(objClassInstance, null); 
    return Convert.ToString(objMethodResult);
}

OUTPUT:

Reflection-Introduction
Reflection-Introduction

Above example explains how to call method using reflection.

Lets understand below points in details
1) System.Activator.CreateInstance() : Used to create object of any class.

var objClassInstance = System.Activator.CreateInstance(AssemblyName, NamespaceName).Unwrap();

2) MemberInfo : Give information about Members from Class.
3) Type.GetMethod() : Method used to create object of method.

MemberInfo[] mInfoMethods = tClsType.GetMember("getstring");

Here in example we have a method which doesn’t contain any parameter, but if we have method which contains parameters we must have to pass parameter array that as below:

miMethod = tClsType.GetMethod(Convert.ToString("getstring"), lstPrms.ToArray());

4) Invoke() : Method used to execute method dynamically. Invoke method requires two  input parameters, first classObject and second parameter array list which contains parameter type. Second parameter is optional.

Lets take example in which we have overloaded methods, and have a look how to call method using Reflection.

Reflection Introduction Example-2 :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReflectionExample
{
    public class ClsClasses
    {
        public string getstring()
        {
            return "Welcome, Sohil Raval !";
        }
        public string getstring(string val)
        {
            return (!string.IsNullOrEmpty(val)) ? val : "No Records Found.";
        }
        public Int32 getstring(Int32 value)
        {
            return (!string.IsNullOrEmpty(Convert.ToString(value))) ? value : 0;
        }
    }
}
private string CallMethodWithParameter()
{
    List<object> lstMthdParams = new List<object>();
    string AssemblyName = "ReflectionExample";   // Here name of Assembly...
    string NamespaceName = "ReflectionExample.ClsClasses";   // Here classname with its NameSpace...
    var objClassInstance = System.Activator.CreateInstance(AssemblyName, NamespaceName).Unwrap();
    object objMethodResult = null;
    MethodInfo miMethod = null;
    Type tClsType = objClassInstance.GetType();
    MemberInfo[] mInfoMethods = tClsType.GetMember("getstring");
    if (mInfoMethods.Length == 1)
    {
        miMethod = tClsType.GetMethod(Convert.ToString("getstring"));  // Here we can get method from respective class...
    }
    else
    {
        List<Type> lstPrms = new List<Type>();
        lstPrms.Add(typeof(System.String));
        //Here we can get method from respective class...
        miMethod = tClsType.GetMethod(Convert.ToString("getstring"), lstPrms.ToArray()); 
    }
    ParameterInfo[] MethodParameter = miMethod.GetParameters();
    foreach (ParameterInfo item in MethodParameter)
    {
        lstMthdParams.Add("");
    }
    objMethodResult = miMethod.Invoke(objClassInstance, lstMthdParams.ToArray());
    return Convert.ToString(objMethodResult);
}

Above Method describes how to call method with parameter. Here ParameterInfo used for fetching parameter name from method. Here in above method we are calling getstring() method which has string as parameter.In above function we are pass passing blank as parameter when we execute above method output given as below :

Reflection-Introduction-1
Reflection-Introduction-1

Here I have describe basics of refection how should it used to execute any method at runtime.

Download source code: Reflection Introduction C#

One comment

Leave a Reply