Reflect a constant?

  • Thread starter Thread starter Jon Davis
  • Start date Start date
J

Jon Davis

I'm trying to use myclass.GetType().GetField("myconst") to get the constant
of an object, but it doesn't work (returns null). How do I retrieve a
constant field's value of a particular class?

Thanks,
Jon
 
BTW my solution requires late binding as such, so don't ask me why I don't
use myclass.myconst.

Jon
 
Jon Davis said:
I'm trying to use myclass.GetType().GetField("myconst") to get the constant
of an object, but it doesn't work (returns null). How do I retrieve a
constant field's value of a particular class?

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

This works, for instance:

using System;

class Test
{
public const int x=5;

static void Main()
{
Console.WriteLine(typeof(Test).GetField("x").GetValue(null));
}
}
 
public class BasePage : System.Web.UI.Page
{
public string SuperEval() {
string ret = "Failure";
System.Reflection.FieldInfo fi = this.GetType().GetField("SuperString");
if (fi != null) ret = (string)fi.GetValue(null);
return ret;
}
}
public class WebForm1 : BasePage
{
private void Page_Load(object sender, System.EventArgs e)
{
Response.Write(SuperEval());
Response.End();
}
public const string SuperString = "Success";
}
 
Jon Davis said:
public class BasePage : System.Web.UI.Page
{
public string SuperEval() {
string ret = "Failure";
System.Reflection.FieldInfo fi = this.GetType().GetField("SuperString");
if (fi != null) ret = (string)fi.GetValue(null);
return ret;
}
}
public class WebForm1 : BasePage
{
private void Page_Load(object sender, System.EventArgs e)
{
Response.Write(SuperEval());
Response.End();
}
public const string SuperString = "Success";
}

It would help if you'd use a console app as an example in future - it
makes it much easier to test. Here's your example re-expressed and
fixed up:

using System;
using System.Reflection;

class Base
{
public const string SuperString = "Success";
}

class Test : Base
{
public const int x=5;

static void Main()
{
Type t = typeof(Test);
FieldInfo info = t.GetField ("SuperString",
BindingFlags.Public |
BindingFlags.Static |
BindingFlags.FlattenHierarchy);
Console.WriteLine (info.GetValue(null));
}
}

You need to specify the binding flags to include FlattenHierarchy -
static members (such as constants) aren't really inherited as such,
they're just available via subtypes. FlattenHierarchy means that static
members up the type hierarchy are returned as well.
 
I used the web app demo because my console app demo was working and my
actual web app wasn't.

Thanks for the clarification on using BindingFlags.

Jon
 
Back
Top