How to find if a member variable is readonly?
Asked Answered
S

2

28
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.

Seethrough answered 31/3, 2013 at 14:14 Comment(0)
S
47

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.

Siloxane answered 31/3, 2013 at 14:17 Comment(5)
Any idea what NonPublic flag is doing here?Seethrough
@Seethrough GetField won't return private fields by default. You need to set this explicitlySiloxane
@Oh yes I get it. I had not noticed your example about private. ThanksSeethrough
+1 for noting that Reflection will not prevent you from writing a readonly field (which is completely counter-intuitive).Polyphagia
@SamGoldberg I agree it's counter-intuitive, but on the other hand it allows ORMs to work, for example, while still having some nice compile-time checks.Selfexplanatory
M
2

f.Attributes should contain FieldAttributes.InitOnly

Mononuclear answered 31/3, 2013 at 14:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.