Search code examples
c#.netreflectionreadonlyfieldinfo

How to find if a member variable is readonly?


class Bla
{
    public readonly int sum;
}

FieldInfo f = type.GetField("sum");
f.??   // what?

How do I find if sum is readonly or not? For properties I can do PropertyInfo.CanWrite to find if the member has write access.


Solution

  • readonly means that field assignment can occur only near field declaration or inside a constructor. So you can use IsInitOnly property on a FieldInfo, which

    Gets a value indicating whether the field can only be set in the body of the constructor

    More details are on the IsInitOnly MSDN article

    FieldInfo f = typeof(Bla).GetField("sum");
    Console.WriteLine(f.IsInitOnly); //return true
    

    Notes: you also can use IsLiteral property to test if the field is compiled time constant. It will return false for readonly field, but true for fields, marked with const.

    Another note: reflection doesn't prevent you from writing into readonly and private field (same is true for public readonly, but I want to show a more restricted case). So the next code examples are valid and won't throw any exceptions:

    class Bla
    {
        //note field is private now
        private readonly int sum = 0;
    }
    

    Now if you get the field and write a value to it (I use BindingFlags to get private non-static fields, because GetField won't return FieldInfo for private fields by default)

    FieldInfo field = typeof(Bla).GetField("sum", BindingFlags.NonPublic |
                                                  BindingFlags.Instance);
    
    var bla = new Bla();
    field.SetValue(bla, 42);
    
    Console.WriteLine(field.GetValue(bla)); //prints 42
    

    All works ok. It will throw an exception only if a field is const.