FieldInfo::IsInitOnly Property
Gets a value indicating whether the field can only be set 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.
Implements
_FieldInfo::IsInitOnlyIf 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.
using namespace System; using namespace System::Reflection; //Make two fields, one public and one read-only. public ref class Myfielda { public: String^ field; Myfielda() : field( "A - public field" ) {} property String^ Field { String^ get() { return field; } void set( String^ value ) { if ( field != value ) { field = value; } } } }; public ref class Myfieldb { private: String^ const field; public: Myfieldb() : field( "B - readonly field" ) {} property String^ Field { String^ get() { return field; } } }; int main() { Console::WriteLine( "\nReflection.FieldInfo" ); Myfielda^ myfielda = gcnew Myfielda; Myfieldb^ myfieldb = gcnew Myfieldb; //Get the Type and FieldInfo. Type^ MyTypea = Type::GetType( "Myfielda" ); FieldInfo^ Myfieldinfoa = MyTypea->GetField( "field", static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance) ); Type^ MyTypeb = Type::GetType( "Myfieldb" ); FieldInfo^ Myfieldinfob = MyTypeb->GetField( "field", static_cast<BindingFlags>(BindingFlags::NonPublic | BindingFlags::Instance) ); //Modify the fields. //Note that 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 state. 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 state. 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
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1