Thursday 16 June 2016

We can access private method using reflection in C# at runtime.



Important Link:-

Description :-


We can access private method using reflection in C# at runtime.

Example:- (without parameter)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClassLibrary1;
using System.Data.SqlClient;
using System.Reflection;

namespace ConsoleApplication1
{
   
    public class car
    {
        private void fun()
        {
            Console.Write("you are accessing private method.");
        }
    }
    class Program 
    {
        static void Main(string[] args)
        {
            car c = new car();
            Type t = typeof(car);
            MethodInfo m = t.GetMethod("fun", BindingFlags.NonPublic | BindingFlags.Instance);
            string[] str = new string[1];
            str[0] = "sushil";
            m.Invoke(c, str);
        }
    }

   
}

Example 2:- (with parameter)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClassLibrary1;
using System.Data.SqlClient;
using System.Reflection;

namespace ConsoleApplication1
{
   
    public class car
    {
        private void fun(string name)
        {
            Console.Write(name);
        }
    }
    class Program 
    {
        static void Main(string[] args)
        {
            car c = new car();
            Type t = typeof(car);
            MethodInfo m = t.GetMethod("fun", BindingFlags.NonPublic | BindingFlags.Instance);
            string[] str = new string[1];
            str[0] = "sushil";
            m.Invoke(c, str);
        }
    }

   
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.