Grey
Grey

Reputation: 45

How to understand myFieldInfo.GetValue(null) when using Reflection?

Here are my code about reflection:

class Program
{
    private static int a = 100;

    static void Main(string[] args)
    {
        Console.WriteLine("a=" + a);

        Type t = typeof(Program);
        FieldInfo myFieldInfo = t.GetField("a",BindingFlags.NonPublic|BindingFlags.Static);
        if (myFieldInfo!=null)
        {
            Console.WriteLine("The current value of a is "+myFieldInfo.GetValue(null)+", please enter a new value:");
            string newValue = Console.ReadLine();
            int newInt;
            if (int.TryParse(newValue,out newInt))
            {
                myFieldInfo.SetValue(null, newInt);
                Console.WriteLine("a=" + a);
            }
        }

    }
}

It can work! But I really don't understand the meaning of the null in the myFieldInfo.GetValue(null)and the myFieldInfo.SetValue(null, newInt);, and I read the MSDN about the FieldInfo.GetValue Method (Object), I found that the Objectmean "The object whose field value will be returned. ". So It really confused me why the parameter should be null?

Upvotes: 2

Views: 364

Answers (2)

Ofir Winegarten
Ofir Winegarten

Reputation: 9365

Because it is static, From MSDN:

If the field is static, obj is ignored. For non-static fields, obj should be an instance of a class that inherits or declares the field

Upvotes: 1

Patrick Hofman
Patrick Hofman

Reputation: 156998

Usually you will put in there the instance you want to get the field value from. Since in your code the field is static, it is not bound to an instance. Hence, the instance parameter can (and should) be null.

Upvotes: 3

Related Questions