FieldInfo.IsInitOnly Property

July 28, 2014

Gets a value that indicates whether the field can be set only in the body of the constructor.

Namespace:  System.Reflection
Assembly:  mscorlib (in mscorlib.dll)

public bool IsInitOnly { get; }

Property Value

Type: System.Boolean
true if the field has the InitOnly attribute set; otherwise, false.

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


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 
 */


Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Windows Phone

Show:
© 2014 Microsoft