Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type.GetFields() - only returning "public const" fields

I want to call Type.GetFields() and only get back fields declared as "public const". I have this so far...

type.GetFields(BindingFlags.Static | BindingFlags.Public)

... but that also includes "public static" fields.

like image 271
Jon Kruger Avatar asked Aug 17 '09 12:08

Jon Kruger


3 Answers

type.GetFields(BindingFlags.Static | BindingFlags.Public).Where(f => f.IsLiteral);
like image 99
Thomas Levesque Avatar answered Nov 12 '22 21:11

Thomas Levesque


Trying checking whether FieldInfo.Attributes includes FieldAttributes.Literal. I haven't checked it, but it sounds right...

(I don't think you can get only constants in a single call to GetFields, but you can filter the results returned that way.)

like image 38
Jon Skeet Avatar answered Nov 12 '22 19:11

Jon Skeet


Starting from .NET 4.5 you can do that

public class ConstTest
{
    private const int ConstField = 123;

    public int GetValueOfConstViaReflection()
    {
        var fields = this.GetType().GetRuntimeFields();
        return (int)fields.First(f => f.Name == nameof(ConstField)).GetValue(null);
    }
}

I checked and it looks like fields has all private consts.

like image 1
Jacek Plesnar Avatar answered Nov 12 '22 20:11

Jacek Plesnar