Try out the following code snip.
namespace ConsoleApplication4
{
public class reflection
{
public const string mstr = "hello world!";
public reflection()
{
}
public static void Main()
{
System.Reflection.FieldInfo fi =
Type.GetType("ConsoleApplication4.reflection") .GetField("mstr");
string temp = (string)fi.GetValue(null);
Console.WriteLine("get string {0}", temp);
}
}
}
"Allan Rojas" <nd****@thecqgl.com> wrote in message
news:Ob*************@TK2MSFTNGP10.phx.gbl...
'Object reference not set to an instance of an object'
The FieldInfo object initialized on the first line of the 'main' method
never finds the field; after execution is still null/empty.
"jennyq" <je**********@yahoo.com> wrote in message
news:eH**************@TK2MSFTNGP12.phx.gbl... Hi, Allan:
try to use GetValue(null) if you want to retrieve static/const
value on class.
"Allan Rojas" <nd****@thecqgl.com> wrote in message
news:uu**************@tk2msftngp13.phx.gbl... Hi there, i'm new to reflection, i'm trying to retrieve a constant value, but my code is not working:
...
public const int XXX = 5;
public void main()
{
System.Reflection.FieldInfo fi = this.GetType().GetField("XXX");
int temp = (int)fi.GetValue(this);
}
...
If i change the 'XXX' declaration to not-a-constant, the value is
retrieved successfully.