Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflecting constant properties/fields in .net [duplicate]

I have a class which looks like as follows:

public class MyConstants
{
    public const int ONE = 1;
    public const int TWO = 2;

    Type thisObject;
    public MyConstants()
    {
        thisObject = this.GetType();
    }

    public void EnumerateConstants()
    {
        PropertyInfo[] thisObjectProperties = thisObject.GetProperties(BindingFlags.Public);
        foreach (PropertyInfo info in thisObjectProperties)
        {
            //need code to find out of the property is a constant
        }
    }
}

Bascially it is trying to reflect itself. I know how to reflect fields ONE, & TWO. But how do I know if it is a constant or not?

like image 917
deostroll Avatar asked Aug 20 '09 20:08

deostroll


1 Answers

That's because they're fields, not properties. Try:

    public void EnumerateConstants() {        
        FieldInfo[] thisObjectProperties = thisObject.GetFields();
        foreach (FieldInfo info in thisObjectProperties) {
            if (info.IsLiteral) {
                //Constant
            }
        }    
    }

Edit: DataDink's right, it's smoother to use IsLiteral

like image 164
Walt W Avatar answered Sep 25 '22 08:09

Walt W