Indicates whether the field can only be set in the body of the constructor.
[Visual Basic] Public ReadOnly Property Is As Boolean [C#] public bool IsInitOnly {get;} [C++] public: __property bool get_IsInitOnly(); [JScript] public function get IsInitOnly() : Boolean;
Read-only. true if the field has the InitOnly attribute set; otherwise, false.
If the returned value is True, the Field may only be initialized, not written to after initilization.
To get the IsInitOnly property, first get the class Type. From the Type, get the FieldInfo. From the FieldInfo, get the IsInitOnly. To access a non public property, in the GetField method, set the BindingFlags to NonPublic.
The IsInitOnly property is set when the FieldAttributes.InitOnly attribute is set.
In the following example, two fields are created. The second field is readonly, has no set accessor, and the IsInit is set to true.
[C#]
//Make two fields, one public and one readonly public class Myfielda { public string field = "A public field"; public string Field{ get{return field;} set{if(field!=value){field=value;}} } } public class Myfieldb { readonly string field = "B readonly field"; public string Field{ get{return field;} } } public class Myfieldinfo { public static int Main() { Console.WriteLine("\nReflection.FieldInfo"); Myfielda Myfielda = new Myfielda(); Myfieldb Myfieldb = new Myfieldb(); //Get the Type and FieldInfo Type MyTypea = Type.GetType("Myfielda"); FieldInfo Myfieldinfoa = MyTypea.GetField("field", BindingFlags.NonPublic); Type MyTypeb = Type.GetType("Myfieldb"); FieldInfo Myfieldinfob = MyTypeb.GetField("field", BindingFlags.NonPublic); //Modify the fields //Note the Myfieldb is not modified, as it is // read only (IsInitOnly is True). Myfielda.field = "A- modified"; //Myfieldb.field = "B- modified"; //For the first field; //Get and Display the Name, field, and IsInitOnly Console.Write("\n{0} - {1}, IsInitOnly = {2} ", MyTypea.FullName, Myfieldinfoa.GetValue(Myfielda), Myfieldinfoa.IsInitOnly); //For the second field; //Get and Display the Name, field, and IsInitOnly Console.Write("\n{0} - {1}, IsInitOnly = {2} ", MyTypeb.FullName, Myfieldinfob.GetValue(Myfieldb), Myfieldinfob.IsInitOnly); return 0; } }
This code produces the following output:
Reflection.FieldInfo Myfielda- A- modified, IsInitOnly = False
Myfieldb- B readonly field, IsInitOnly = True
FieldInfo Class | FieldInfo Members | System.Reflection Namespace | FieldAttributes