I have been through the below code . Here i am not able to get/set the value of the variable during runtime . Variable value has been taken through console .
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace ReflectionTest
{
class Addition
{
public int a = 5, b = 10, c = 20;
public Addition(int a)
{
Console.WriteLine("Constructor called, a={0}", a);
}
public Addition()
{
Console.WriteLine("Hello");
}
protected Addition(string str)
{
Console.WriteLine("Hello");
}
}
class Test
{
static void Main()
{
//changing variable value during run time
Addition add = new Addition();
Console.WriteLine("a + b + c = " + (add.a + add.b + add.c));
Console.WriteLine("Please enter the name of the variable that you wish to change:");
string varName = Console.ReadLine();
Type t = typeof(Addition);
FieldInfo fieldInfo = t.GetField(varName ,BindingFlags.Public);
if (fieldInfo != null)
{
Console.WriteLine("The current value of " + fieldInfo.Name + " is " + fieldInfo.GetValue(add) + ". You may enter a new value now:");
string newValue = Console.ReadLine();
int newInt;
if (int.TryParse(newValue, out newInt))
{
fieldInfo.SetValue(add, newInt);
Console.WriteLine("a + b + c = " + (add.a + add.b + add.c));
}
Console.ReadKey();
}
}
}
}
Thanks in advance ..