ASP.NET

Reflection in Asp.Net C#

Reflection in Asp.Net C#

Reflection in Asp.Net C#

Reflection is needed:-
1. when You want to determine or inspect the content/metadata of an assembly like what are the methods in that assembly, what are the properties in that assembly, are they public, are they private, etc.
2. To create an instance of a type dynamically, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.

One of the biggest implementations of Reflection is Visual Studio itself.
Suppose, in visual studio, we create an object of the String class, and when we press obj. then visual studio intelligence shows all the properties, methods, fields.
This is possible because of the Reflection in C#.


How to Implement Reflection in C#?

1. Create a Console applicaiton - ReflectionDemo
2. Add a class library project into this project ReflectionClasLib
3. build the Class Library Project and check its DLL inside ReflectionClasLib Project’s bin=> Debug location

public class Class1
{
    public int Variable1;
    private int Variable2;
    public int Property1 { get; set; }
    private int Property2 { get; set; }
    public void Method1()
    {
        Console.WriteLine("Method1 Invoked");
    }
    private void Method2()
    {
        Console.WriteLine("Method2 Invoked");
    }
}


4. Now, remove the Class Library Project from the solution: Right-click on the Class Library Project and then click on the Remove option, Choose Yes on confirmation dialog box

Now what, Now we want to Browse the Properties, Methods, and Variables of ReflectionClasLib DLL Assembly inside our ReflectionDemo Console application, How?

Solution: We can do so using Reflection
How? Implementing reflection is a three steps process.
Step1: Import the Reflection Namespace
Step2: Get the Type of the Object/ Reference of the assembly / DLL
       To get the reference of the assembly we need to use the Assembly.Loadfile method and we need to provide the Path of the assembly
       Once we get the Assembly Reference, we can easly fetch the metadata below using some simple steps, as showing below      
Step3: Browse the Metadata of the Object

namespace ReflectionDemo
{
    using System.Data;
    // Step1: Import the Reflection namespace
    using System.Reflection;
    using System.Xml.Linq;

    internal class Program
    {
        static void Main(string[] args)
        {
            //Get the Assembly Reference
            var ClassLibAssembly = Assembly.LoadFile(@"D:\CodeCollection\PracticeCodeCollection\VSCodeParctice\ReflectionDemo\ReflectionClasLib\bin\Debug\netcoreapp3.1\ReflectionClasLib.dll");

            //Get the Class Reference
            var ReflectionClassType = ClassLibAssembly.GetType("ReflectionClasLib.Class1");

            //Create an instance of the Class type
            dynamic ReflectionClassObject = Activator.CreateInstance(ReflectionClassType);

            //Get the Type of the Instance
            Type ParameterType = ReflectionClassObject.GetType();


            //Step3: Browse the Metadata
            //Get all Public Fields/ variables          
            foreach (MemberInfo memberInfo in ParameterType.GetFields()) {
                Console.WriteLine(memberInfo.Name);
            }

            //Get all Public Methods          
            foreach (MemberInfo memberInfo in ParameterType.GetMethods()) {
                Console.WriteLine(memberInfo.Name);
            }

            //Get all Public Properties           
            foreach (MemberInfo memberInfo in ParameterType.GetProperties()) {
                Console.WriteLine(memberInfo.Name);
            }

            Console.ReadKey();
        }
    }
}

GetFields(): It returns all the public fields of the current System.Type.
GetProperties(): It returns all the public properties of the current System.Type.
GetMethods(): It returns all the public methods of the current System.Type.
GetMembers(): It returns all the public members of the current System.Type.


Get Type Details using Reflection in C#:
Once we get the Type then we want to show the class name, fully qualified class name, and namespace name. For this, we need to call the Name, FullName, and Namespace properties

internal class Program
{
    static void Main(string[] args)
    {
        //Get the Assembly Reference
        var ClassLibAssembly = Assembly.LoadFile(@"D:\CodeCollection\PracticeCodeCollection\VSCodeParctice\ReflectionDemo\ReflectionClasLib\bin\Debug\netcoreapp3.1\ReflectionClasLib.dll");

        //Get the Class Reference
        var ReflectionClassType = ClassLibAssembly.GetType("ReflectionClasLib.Class1");

        //Step3: Browse the Metadata
        // Print the Type details
        Console.WriteLine($"Full Name = {ReflectionClassType.FullName}");
        Console.WriteLine($"Just the Class Name = {ReflectionClassType.Name}");
        Console.WriteLine($"Just the Namespace Name = {ReflectionClassType.Namespace}");

        Console.ReadKey();
    }
}



Invoke Methods Dynamically Using Reflection in C#?
To invoke the assembly method using reflection, we need to use the InvokeMember method,
This method invokes the specified member, using the specified binding constraints and matching the specified argument list. It returns an object representing the return value of the invoked member.

internal class Program
{
    static void Main(string[] args)
    {
        //Get the Assembly Reference
        var ClassLibAssembly = Assembly.LoadFile(@"D:\CodeCollection\PracticeCodeCollection\VSCodeParctice\ReflectionDemo\ReflectionClasLib\bin\Debug\netcoreapp3.1\ReflectionClasLib.dll");

        //Get the Class Reference
        var ReflectionClassType = ClassLibAssembly.GetType("ReflectionClasLib.Class1");

        //Create an instance of the Class type
        dynamic ReflectionClassObject = Activator.CreateInstance(ReflectionClassType);

        //Get the Type of the Instance
        Type ParameterType = ReflectionClassObject.GetType();

        // Invoke Method
        ParameterType.InvokeMember(
            "Method1",
            BindingFlags.Public |
            BindingFlags.InvokeMethod |
            BindingFlags.Instance,
            null, ReflectionClassObject, null);

        Console.ReadKey();
    }
}

name: The string containing the name of the constructor, method, property, or field member to invoke. In our case it is Method1.
invokeAttr: A bitmask comprised of one or more System.Reflection.BindingFlags that specify how the search is conducted. The access can be one of the BindingFlags such as Public, NonPublic, Private, InvokeMethod, GetField, and so on. The type of lookup need not be specified. If the type of lookup is omitted, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static is used.
binder: An object that defines a set of properties and enables binding, which can involve the selection of an overloaded method, coercion of argument types, and invocation of a member through reflection. -or- A null reference to use the System.Type.DefaultBinder. Note that explicitly defining a System.Reflection.Binder objects may be required for successfully invoking method overloads with variable arguments. Here, we are passing a null value.
target: The object on which to invoke the specified member. In our example, the object is MyObject.
args: An array containing the arguments to pass to the member to invoke. As our method does not take any arguments, we pass null here.













Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram