Luis
Luis

Reputation: 2715

GetField returning null

i'm trying to getField but is always returning null Here's a image of the code and the watchs of the variables.

Code: FieldInfo xSortField = xFieldInfo.GetValue(x).GetType().GetField(this.prefixedSortBy[i]);

enter image description here

Upvotes: 7

Views: 12172

Answers (4)

Yonathan Druck
Yonathan Druck

Reputation: 21

In addition to previous answers there is a clear distinction between Fields and Properties. Trying to get a property but using GetField() will result in null.

To get property Info:

var property = obj.GetType().GetProperty(fieldName);

to get value of field/property you can use a method like this:

public static T? GetFieldValue<T>(object obj, string fieldName)
        where T : struct
    {
        var property = obj.GetType().GetProperty(fieldName);
        if (property != null)
        {
            if (property.PropertyType == typeof(T))
            {
                return (T)property.GetValue(obj);
            }

            return null;
        }

        var field = obj.GetType().GetField(fieldName);
        if (field != null && field.FieldType == typeof(T))
        {
            return (T)field.GetValue(obj);
        }

        return null;
    }

Upvotes: 1

Charles Mager
Charles Mager

Reputation: 26213

I think you need to look more closely at what you're doing, as it doesn't seem to make much sense.

xFieldInfo.GetValue(x) returns a boxed integer 2. GetType() then returns typeof(int)

You're then trying to get the FieldInfo for the field ssId on int. That doesn't exist.

It looks like you intended this:

FieldInfo xSortField = x.GetType().GetField(this.prefixedSortBy[i])

Upvotes: 5

f14shm4n
f14shm4n

Reputation: 461

You need to use BindingFlags

GetField("FieldName", BindingFlags.Instance | BindingFlags.Public);

Upvotes: 10

Andrey Korneyev
Andrey Korneyev

Reputation: 26876

You must specify either BindingFlags.Instance or BindingFlags.Static as a second argument in order to get a return value.

Also BindingFlags.NonPublic should be used to get non-public fields.

See MSDN for reference.

Upvotes: 7

Related Questions