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

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;
}
 
E

Ed Kaim [MSFT]

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.
 
P

Patrick Steele [MVP]

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);
}
}
 
J

Jiho Han

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);
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top