FieldInfo.IsInitOnly Property


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

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

Public ReadOnly Property IsInitOnly As Boolean

Property Value

Type: System.Boolean

true if the field has the InitOnly attribute set; otherwise, false.

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. To access a non-public field, combine BindingFlags.NonPublic with either or both of BindingFlags.Static and BindingFlags.Instance in the GetField method.

The IsInitOnly property is set when the FieldAttributes.InitOnly attribute is set.

In the following example, two fields are created. The second field is read-only, having no set accessor, and IsInitOnly is set to true.

Imports System
Imports System.Reflection
Imports Microsoft.VisualBasic

'Make two fields, one public and one read-only.
Public Class Myfielda
    Public field As String = "A - public modifiable field"
End Class 'Myfielda

Public Class Myfieldb
    Public ReadOnly field As String = "B - readonly field"
End Class 'Myfieldb

Public Class Myfieldinfo
    Public Shared Function Main() As Integer
        Dim Myfielda As New Myfielda()
        Dim Myfieldb As New Myfieldb()

        'Get the Type and FieldInfo.
        Dim MyTypea As Type = GetType(Myfielda)
        Dim Myfieldinfoa As FieldInfo = MyTypea.GetField("field", _
            BindingFlags.Public Or BindingFlags.Instance)
        Dim MyTypeb As Type = GetType(Myfieldb)
        Dim Myfieldinfob As FieldInfo = MyTypeb.GetField("field", _
            BindingFlags.Public Or BindingFlags.Instance)

        'Modify the fields.
        'Note that Myfieldb is not modified, as it is
        'read-only (IsInitOnly is True).
        Myfielda.field = "A - modified"
        'For the first field, get and display the name, field, and IsInitOnly state.
        Console.WriteLine("{0} - {1}, IsInitOnly = {2} ", MyTypea.FullName, _
            Myfieldinfoa.GetValue(Myfielda), Myfieldinfoa.IsInitOnly)
        'For the second field get and display the name, field, and IsInitOnly state.
        Console.WriteLine("{0} - {1}, IsInitOnly = {2} ", MyTypeb.FullName, _
            Myfieldinfob.GetValue(Myfieldb), Myfieldinfob.IsInitOnly)

        Return 0
    End Function 'Main
End Class 'Myfieldinfo

This code produces the following output:


Myfielda - A- modified, IsInitOnly = False

Myfieldb - B readonly field, IsInitOnly = True

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top