FieldInfo.IsInitOnly Property
[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]
Gets a value that indicates whether the field can be set only in the body of the constructor.
Assembly: mscorlib (in mscorlib.dll)
Property Value
Type: System.Booleantrue if the field has the InitOnly attribute set; otherwise, false.
| Exception | Condition |
|---|---|
| MethodAccessException | This member is invoked late-bound through mechanisms such as Type.InvokeMember. |
If the returned value is true, the field can only be initialized, and is read-only thereafter.
To get the IsInitOnly property, first get the class Type. From the Type, get the FieldInfo. From the FieldInfo, get the IsInitOnly property.
The IsInitOnly property is true when the FieldAttributes.InitOnly attribute is set.
In the following example, two fields are created. The second field is read-only (that is, it has no set accessor), and therefore the value of IsInitOnly is true.
Note: |
|---|
To run this example, see Building examples that have static TextBlock controls for Windows Phone 8. |
using System; using System.Reflection; public class Example { //Make two public fields, one read-only. public string Myfielda = "A - public modifiable field"; public readonly string Myfieldb = "B - readonly field"; public static void Demo(System.Windows.Controls.TextBlock outputBlock) { outputBlock.Text += "Reflection.FieldInfo\n\n"; Example ex = new Example(); //Get the Type and FieldInfo. Type myType = typeof(Example); FieldInfo fa = myType.GetField("Myfielda", BindingFlags.Public | BindingFlags.Instance); FieldInfo fb = myType.GetField("Myfieldb", BindingFlags.Public | BindingFlags.Instance); //Modify the field that is not read-only (that is, the field for which //IsInitOnly is False). ex.Myfielda = "A - modified"; //For the first field, get and display the name, field, and IsInitOnly state. outputBlock.Text += String.Format("{0} - \"{1}\", IsInitOnly = {2} \n", fa.Name, fa.GetValue(ex), fa.IsInitOnly); //For the second field get and display the name, field, and IsInitOnly state. outputBlock.Text += String.Format("{0} - \"{1}\", IsInitOnly = {2} \n", fb.Name, fb.GetValue(ex), fb.IsInitOnly); } } /*This code produces the following output: Reflection.FieldInfo Myfielda - "A - modified", IsInitOnly = False Myfieldb - "B - readonly field", IsInitOnly = True */
Note: