1

I want to access the FieldInfo, for the CustomAttributes that are on a field, and other purposes, but I'd prefer not to use a string to access that field, nor to have to run through all the fields in a class.

If I simply have,

class MyClass
{
#pragma warning disable 0414, 0612, 0618, 0649
    private int myInt;
#pragma warning restore 0414, 0612, 0618, 0649

    public MyClass()
    {
        BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
        Console.WriteLine( GetType().GetField("myInt", flags) );

        foreach( FieldInfo fi in GetType().GetFields(flags) )
        {
            Console.WriteLine( string.Format("{0} {1} {2}", fi.Name, myInt, fi.GetValue(this) ) );
        }
    }
}

I know I can access the FieldInfo of "myInt" directly via the "GetField" function, if I have the string of it's name, or cycling through "GetFields", that would again rely upon having the string "myInt" to ensure you've the right field.

Is there any sort of magic that's available like ref myInt, or out myInt, or some keyword that I don't know about yet which would give me access, or am I limited to needing the string name to get it?

seaders
  • 3,878
  • 3
  • 40
  • 64

2 Answers2

2

Do you mean getting the memberinfo from a compiled expression rather than the string? e.g

class Program
{
    public static void Main()
    {
        var cls = new MyClass();
        Console.WriteLine(GetMemberInfo(cls, c => c.myInt));
        Console.ReadLine();
    }

    private static MemberInfo GetMemberInfo<TModel, TItem>(TModel model, Expression<Func<TModel, TItem>> expr)
    {
        return ((MemberExpression)expr.Body).Member;
    }

    public class MyClass
    {
        public int myInt;   
    }
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
James Simpson
  • 1,150
  • 6
  • 11
1

In C# 6 (you can get the CTP here) there is the nameof(...) operator - you'd use:

string name = nameof(myInt);
var fieldInfo = GetType().GetField(name, flags);

Is that an option for you, or must you use C# 5.0 (.NET 4.5)?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
  • Helpful, and potentially the right answer for some, but #6 isn't an option for me at the moment, but I will use this method when it eventually is. Thanks. – seaders Feb 26 '15 at 23:11
  • No problem. The method @JamesSimpson posted is what we use where I work (and it does work well). – Wai Ha Lee Feb 26 '15 at 23:36