Monday, January 5, 2015

How to change the variable value during Run Time( Reflection)

 private static string a = "uday";  
 private static string b = "kittu";
        static void Main(string[] args)
        {
            Console.WriteLine(a);
            Console.WriteLine(b);
            Console.WriteLine("Please enter the name of the variable that you wish to change:");
            //a = Console.ReadLine();
            string varName = Console.ReadLine();
            Type t = typeof(Program);
            FieldInfo fieldInfo = t.GetField(varName, BindingFlags.NonPublic | BindingFlags.Static);
            if (fieldInfo != null)
            {
                Console.WriteLine("The current value of " + fieldInfo.Name + " is " + fieldInfo.GetValue(null) + ". You may enter a new value now:");
                string newValue = Console.ReadLine();
                fieldInfo.SetValue(null, newValue);
                Console.WriteLine("a " + (a));
                Console.WriteLine("b " + (b));
            }
            Console.ReadKey();
        }

Output:





namespace ConsoleApplication1

{
    class Program
    {
        private static int a = 5, b = 10, c = 20;
        static void Main(string[] args)
        {
            Console.WriteLine("a + b + c = " + (a + b + c));
            Console.WriteLine("Please enter the name of the variable that you wish to change:");
            string varName = Console.ReadLine();
            Type t = typeof(Program);
            FieldInfo fieldInfo = t.GetField(varName, BindingFlags.NonPublic | BindingFlags.Static);
            if (fieldInfo != null)
            {
                Console.WriteLine("The current value of " + fieldInfo.Name + " is " + fieldInfo.GetValue(null) + ". You may enter a new value now:");
                string newValue = Console.ReadLine();
                int newInt;
                if (int.TryParse(newValue, out newInt))
                {
                    fieldInfo.SetValue(null, newInt);
                    Console.WriteLine("a + b + c = " + (a + b + c));
                }
                Console.ReadKey();
            }
        }

    }

}

Output:







No comments:

Post a Comment

Thank you for visiting my blog

Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...