retrieving the list of public constants of a class? and possibly their integer values?

  • Thread starter Thread starter Jiho Han
  • Start date Start date
J

Jiho Han

I am trying to retrieve the list of integer constants for a class.

I've tried to retrieve them by using TypeDescriptor.GetProperties but with
no success.
How can I get the list of declared constants or given the name of a constant
(i.e. "ABC"), retrieve its integer value?
Thanks much.
Jiho

PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(MyClass));

public class MyClass
{
public const int ABC = 1;
public const int DEF = 1000;
}
 
I don't know if the constants are available after compilation. The compiler
may optimize them out for actual constant values. I believe native C++ does
this, but I don't know about for managed code.

If you want to access constant values defined in code, you should consider
using static constant variables instead.
 
I am trying to retrieve the list of integer constants for a class.

I've tried to retrieve them by using TypeDescriptor.GetProperties but with
no success.
How can I get the list of declared constants or given the name of a constant
(i.e. "ABC"), retrieve its integer value?

Use reflection (System.Reflection namespace):

MyClass x = new MyClass();

FieldInfo[] f = x.GetType().GetFields();
foreach(FieldInfo fi in f)
{
if( fi.IsLiteral )
{
object val = fi.GetValue(x);
int ival = Int32.Parse(val.ToString());
Console.WriteLine("{0} = {1}", fi.Name, ival);
}
}
 
Thanks. I had figured this out just a while ago. However, I was not using
IsLiteral to filter the list of fields returned. Luckily for me, the class
I am using does not contain anything other than constants.
However, I will change my code to use IsLiteral.

Thanks all.
Jiho

Patrick Steele said:
I am trying to retrieve the list of integer constants for a class.

I've tried to retrieve them by using TypeDescriptor.GetProperties but with
no success.
How can I get the list of declared constants or given the name of a constant
(i.e. "ABC"), retrieve its integer value?

Use reflection (System.Reflection namespace):

MyClass x = new MyClass();

FieldInfo[] f = x.GetType().GetFields();
foreach(FieldInfo fi in f)
{
if( fi.IsLiteral )
{
object val = fi.GetValue(x);
int ival = Int32.Parse(val.ToString());
Console.WriteLine("{0} = {1}", fi.Name, ival);
}
}
 
Back
Top