System.Reflection.Emit.FieldBuilder Class

Assembly: Mscorlib.dll
Namespace: System.Reflection.Emit
Summary
Defines and represents a field. This class cannot be inherited.
C# Syntax:
public sealed class FieldBuilder : FieldInfo
Thread Safety
Reflection Emit is thread-safe when using assemblies that were created with the AppDomain.DefineDynamicAssembly method with the Boolean parameter isSynchronized set to true.
Remarks
Get an instance of FieldBuilder by calling TypeBuilder.DefineField, ModuleBuilder.DefineInitializedData, or ModuleBuilder.DefineUninitializedData.
See also:
System.Reflection.Emit Namespace

System.Reflection.Emit.FieldBuilder Member List:

Public Properties
Attributes Read-only

Overridden:
Indicates the attributes of this field. This property is read-only.
DeclaringType Read-only

Overridden:
Indicates a reference to the Type object for the type that declares this field. This property is read-only.
FieldHandle Read-only

Overridden:
Indicates the internal metadata handle for this field. This property is read-only.
FieldType Read-only

Overridden:
Indicates the Type object that represents the type of this field. This property is read-only.
IsAssembly
(inherited from System.Reflection.FieldInfo)
Read-only

See base class member description: System.Reflection.FieldInfo.IsAssembly


Gets a value indicating whether this field has Assembly level visibility.
IsFamily
(inherited from System.Reflection.FieldInfo)
Read-only

See base class member description: System.Reflection.FieldInfo.IsFamily


Gets a value indicating whether this field has Family level visibility.
IsFamilyAndAssembly
(inherited from System.Reflection.FieldInfo)
Read-only

See base class member description: System.Reflection.FieldInfo.IsFamilyAndAssembly


Gets a value indicating whether this field has FamilyAndAssembly level visibility.
IsFamilyOrAssembly
(inherited from System.Reflection.FieldInfo)
Read-only

See base class member description: System.Reflection.FieldInfo.IsFamilyOrAssembly


Gets a value indicating whether this field has FamilyOrAssembly level visibility.
IsInitOnly
(inherited from System.Reflection.FieldInfo)
Read-only

See base class member description: System.Reflection.FieldInfo.IsInitOnly


Gets a value indicating whether the field can only be set in the body of the constructor.
IsLiteral
(inherited from System.Reflection.FieldInfo)
Read-only

See base class member description: System.Reflection.FieldInfo.IsLiteral


Gets a value indicating whether the value is written at compile time and cannot be changed.
IsNotSerialized
(inherited from System.Reflection.FieldInfo)
Read-only

See base class member description: System.Reflection.FieldInfo.IsNotSerialized


Gets a value indicating whether this field has the NotSerialized attribute.
IsPinvokeImpl
(inherited from System.Reflection.FieldInfo)
Read-only

See base class member description: System.Reflection.FieldInfo.IsPinvokeImpl


Gets a value indicating whether the corresponding PinvokeImpl attribute is set in FieldAttributes.
IsPrivate
(inherited from System.Reflection.FieldInfo)
Read-only

See base class member description: System.Reflection.FieldInfo.IsPrivate


Gets a value indicating whether the field is private.
IsPublic
(inherited from System.Reflection.FieldInfo)
Read-only

See base class member description: System.Reflection.FieldInfo.IsPublic


Gets a value indicating whether the field is public.
IsSpecialName
(inherited from System.Reflection.FieldInfo)
Read-only

See base class member description: System.Reflection.FieldInfo.IsSpecialName


Gets a value indicating whether the corresponding SpecialName attribute is set in the FieldAttributes enumerator.
IsStatic
(inherited from System.Reflection.FieldInfo)
Read-only

See base class member description: System.Reflection.FieldInfo.IsStatic


Gets a value indicating whether the field is static.
MemberType
(inherited from System.Reflection.FieldInfo)
Read-only

See base class member description: System.Reflection.FieldInfo.MemberType


Gets the Type of property reflected by this FieldInfo object. The retrieved value indicates that this member is a field.
Name Read-only

Overridden:
Indicates the name of this field. This property is read-only.
ReflectedType Read-only

Overridden:
Indicates the reference to the Type object from which this object was obtained. This property is read-only.
Public Methods
Equals
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
GetCustomAttributes Overloaded:
GetCustomAttributes(bool inherit)

Overridden:
Returns all the custom attributes defined for this field.
GetCustomAttributes Overloaded:
GetCustomAttributes(Type attributeType, bool inherit)

Overridden:
Returns all the custom attributes defined for this field identified by the given type.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
GetToken Returns the token representing this field.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
GetValue Overridden:
Retrieves the value of the field supported by the given object.
GetValueDirect
(inherited from System.Reflection.FieldInfo)
See base class member description: System.Reflection.FieldInfo.GetValueDirect


Returns the value of a field supported by a given object.
IsDefined Overridden:
Indicates whether an attribute having the specified type is defined on a field.
SetConstant Sets the default value of this field.
SetCustomAttribute Overloaded:
SetCustomAttribute(CustomAttributeBuilder customBuilder)

Sets a custom attribute using a custom attribute builder.
SetCustomAttribute Overloaded:
SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)

Sets a custom attribute using a specified custom attribute blob.
SetMarshal Describes the native marshaling of the field.
SetOffset Specifies the field layout.
SetValue
(inherited from System.Reflection.FieldInfo)
Overloaded:
SetValue(object obj, object value)

See base class member description: System.Reflection.FieldInfo.SetValue


Sets the value of the field supported by the given object.
SetValue Overloaded:
SetValue(object obj, object val, BindingFlags invokeAttr, Binder binder, CultureInfo culture)

Overridden:
Sets the value of the field supported by the given object.
SetValueDirect
(inherited from System.Reflection.FieldInfo)
See base class member description: System.Reflection.FieldInfo.SetValueDirect


Sets the value of the field supported by the given object.
ToString
(inherited from System.Object)
See base class member description: System.Object.ToString

Derived from System.Object, the primary base class for all objects.
Protected Methods
Finalize
(inherited from System.Object)
See base class member description: System.Object.Finalize

Derived from System.Object, the primary base class for all objects.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.

Hierarchy:


System.Reflection.Emit.FieldBuilder Member Details

Overridden Property: Attributes (read-only)
Summary
Indicates the attributes of this field. This property is read-only.
C# Syntax:
public override FieldAttributes Attributes {get;}

Return to top


Overridden Property: DeclaringType (read-only)
Summary
Indicates a reference to the Type object for the type that declares this field. This property is read-only.
C# Syntax:
public override Type DeclaringType {get;}

Return to top


Overridden Property: FieldHandle (read-only)
Summary
Indicates the internal metadata handle for this field. This property is read-only.
C# Syntax:
public override RuntimeFieldHandle FieldHandle {get;}
Exceptions
Exception Type Condition
NotSupportedException This method is not supported.

Return to top


Overridden Property: FieldType (read-only)
Summary
Indicates the Type object that represents the type of this field. This property is read-only.
C# Syntax:
public override Type FieldType {get;}

Return to top


Property: IsAssembly (read-only)
Inherited
See base class member description: System.Reflection.FieldInfo.IsAssembly

Summary
Gets a value indicating whether this field has Assembly level visibility.
C# Syntax:
public bool IsAssembly {get;}
Remarks
If a field has Assembly level visibility, it can be called from any member within that assembly, but none outside of it.

The IsAssembly property is set when the FieldAttributes.Assembly attribute is set. In C#, you can declare the field as internal to set this property to limit the access of this field to this project.

Example
 //Make two fields.
 public class Myfielda
 {
    private string field = "A private field";
    public string Field{
       get{return field;}
       set{if(field!=value){field=value;}}
    }
 }

 public class Myfieldb
 {
    internal string field = "B public field";
    public string Field{
       get{return field;}
       set{if(field!=value){field=value;}}
    }
 }
 
 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|BindingFlags.Instance);
       Type MyTypeb = Type.GetType("Myfieldb");
       FieldInfo Myfieldinfob = MyTypeb.GetField("field", BindingFlags.NonPublic|BindingFlags.Instance);
  
       //For the first field, get and display the name, field, and IsAssembly.
       Console.Write("\n{0} - ", MyTypea.FullName);
       Console.Write("{0};", Myfieldinfoa.GetValue(Myfielda));
       Console.Write(" IsAssembly = {0}; ", Myfieldinfoa.IsAssembly );
       if (Myfieldinfoa.IsAssembly)
          Console.Write("Field has limited accessibility");
  
       //For the second field, get and display the name, field, and IsAssembly.
 
       Console.Write("\n{0} - ", MyTypeb.FullName);
       Console.Write("{0}; ", Myfieldinfob.GetValue(Myfieldb));
       Console.Write(" IsAssembly = {0}; ", Myfieldinfob.IsAssembly );
       if (Myfieldinfob.IsAssembly)
          Console.Write("Field has limited accessibility");
  
       return 0;
    }
 }

    
This code produces the following output:
              				Reflection.FieldInfo
              				Myfielda - A private field; IsAssembly = False;
              				Myfieldb - B public field; IsAssembly = True; Field has limited accessibility
              			
            
See also:
FieldAttributes

Return to top


Property: IsFamily (read-only)
Inherited
See base class member description: System.Reflection.FieldInfo.IsFamily

Summary
Gets a value indicating whether this field has Family level visibility.
C# Syntax:
public bool IsFamily {get;}
Remarks
This property can be called from any member in a derived class, but not from any other type.

To get the IsFamily property, first get the class Type. From the Type, get the FieldInfo. From the FieldInfo, get the IsFamily value.

The IsFamily property is set when the FieldAttributes.Family attribute is set.

Example
In the following example, two properties are created. The first property has a private string field and the second property has a protected string field, resulting in the IsFamily property being set to true.
 //Make two fields.
 using System;
 using System.Reflection;
 
 public class Myfielda
 {
    private string field = "A private field";
    public string Field{
       get{return field;}
       set{if(field!=value){field=value;}}
    }
 }
 
 public class Myfieldb
 {
    protected string field = "B public field";
    public string Field{
       get{return field;}
       set{if(field!=value){field=value;}}
    }
 }
  
 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|BindingFlags.Instance);
       Type MyTypeb = Type.GetType("Myfieldb");
       FieldInfo Myfieldinfob = MyTypeb.GetField("field",
          BindingFlags.NonPublic|BindingFlags.Instance);
  
       //For the first field, get and display the Name, field, and IsFamily.
       Console.Write("\n{0} - ", MyTypea.FullName);
       Console.Write("{0} - ", Myfieldinfoa.GetValue(Myfielda));
       Console.Write("\n  IsFamily - {0}", Myfieldinfoa.IsFamily);
       Console.Write("\n  FieldAttributes - {0}",
          Myfieldinfoa.Attributes.ToString());
  
       //For the second field, get and Display the Name, field, and IsFamily.
       Console.Write("\n{0} - ", MyTypeb.FullName);
       Console.Write("{0} - ", Myfieldinfob.GetValue(Myfieldb));
       Console.Write("\n  IsFamily - {0}", Myfieldinfob.IsFamily);
       FieldAttributes Myfieldattributesb = Myfieldinfob.Attributes;
       Console.Write("\n  FieldAttributes - {0}",
          Myfieldinfob.Attributes.ToString());
  
       return 0;
    }
 }

    

This code produces the following output:

              				Reflection.FieldInfo
              				Myfielda - A private field -
              				IsFamily - False
              				FieldAttributes - Private
              				Myfieldb - B public field -
              				IsFamily - True
              				FieldAttributes - Family
              			
            
See also:
FieldAttributes | Type

Return to top


Property: IsFamilyAndAssembly (read-only)
Inherited
See base class member description: System.Reflection.FieldInfo.IsFamilyAndAssembly

Summary
Gets a value indicating whether this field has FamilyAndAssembly level visibility.
C# Syntax:
public bool IsFamilyAndAssembly {get;}
Remarks
If a field has FamilyAndAssembly level visibility, it can be called from any member in a derived class that is also in the same assembly, but not from any other type.

The IsFamilyAndAssembly property is set when the FieldAttributes.FamANDAssem attribute is set.

Example
using System;
using System.Reflection;

public class Fieldinfo_IsFamilyAndAssembly
{
   protected internal string myField = "A protected internal field";
   
   public static void Main()
   {
      Fieldinfo_IsFamilyAndAssembly myObject = new 
         Fieldinfo_IsFamilyAndAssembly();

      //Get the Type and FieldInfo.
      Type myType1 = typeof(Fieldinfo_IsFamilyAndAssembly);
      FieldInfo myFieldInfo = myType1.GetField("myField",
         BindingFlags.NonPublic|BindingFlags.Instance);

      // Display the name, field and the FamilyAndAssembly attribute for the field.
      Console.Write("\n Name of Class: {0}", myType1.FullName);
      Console.Write("\n Value of Field: {0}", myFieldInfo.GetValue(myObject));
      Console.Write("\n IsFamilyAndAssembly: {0}", 
         myFieldInfo.IsFamilyAndAssembly );
   }
}

    
See also:
FieldAttributes

Return to top


Property: IsFamilyOrAssembly (read-only)
Inherited
See base class member description: System.Reflection.FieldInfo.IsFamilyOrAssembly

Summary
Gets a value indicating whether this field has FamilyOrAssembly level visibility.
C# Syntax:
public bool IsFamilyOrAssembly {get;}
Remarks
If a field has FamilyOrAssembly level visibility, it can be called from any member in a derived class or any member in the same assembly, but not from any other type. The IsFamilyOrAssembly property is set when the FieldAttributes.FamORAssem attribute is set.
Example
In the following example, two fields are created. The second field, Myfieldb is derived from the first, Myfielda. The Myfielda.field is protected internal, which allows Myfieldb.field to be derived. If Myfielda.field was a private field, Myfieldb.field could not be derived.

using System;
using System.Reflection;


 //Make two fields.
 public class Myfielda
    //Note that if the private line below is uncommented
    //and the protected internal line below is commented out,
    //this will not compile as Myfielda.field is inaccessible.
 {
    //private string field = "A private field";
    protected internal string field = "A private field";
    public string Field{
       get{return field;}
       set{if(field!=value) {field=value;}}
    }
 }

 //Myfieldb is derived from Myfielda.
 //The protected internal string field allows
 //the IsFamilyOrAssembly flag to be set and allows
 //the field to be visible from a derived class.
 public class Myfieldb:Myfielda
 {
    new public string Field{
       get{return field;}
       set{if(field!=value){field=value;}}
    }
 }
 
 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|BindingFlags.Instance);
       Type MyTypeb = Type.GetType("Myfieldb");
       FieldInfo Myfieldinfob = MyTypeb.GetField("field",
          BindingFlags.NonPublic|BindingFlags.Instance);
       
       //For the first field, get and display the Name, field, and
       //IsFamilyOrAssembly.
       Console.Write("\n{0} - ", MyTypea.FullName);
       Console.Write("{0};", Myfieldinfoa.GetValue(Myfielda));
       Console.Write("\n   IsFamilyOrAssembly = {0};",
          Myfieldinfoa.IsFamilyOrAssembly);
       if (Myfieldinfoa.IsFamilyOrAssembly )
          Console.Write("Field has limited accessibility");
  
       //For the second field, get and display the name and field.
       Console.Write("\n{0} - ", MyTypeb.FullName);
       Console.Write("{0}; ", Myfieldinfob.GetValue(Myfieldb));
  
       return 0;
    }
 }

    

This code produces the following output:

              				Reflection.FieldInfo
              				Myfielda - A private field; IsFamilyOrAssembly = True; Field has limited accessibility 
              				Myfieldb - A private field;
              			
            
See also:
FieldAttributes

Return to top


Property: IsInitOnly (read-only)
Inherited
See base class member description: System.Reflection.FieldInfo.IsInitOnly

Summary
Gets a value indicating whether the field can only be set in the body of the constructor.
C# Syntax:
public bool IsInitOnly {get;}
Remarks
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, set the BindingFlags to NonPublic and choose either Static or InstanceBindingFlags in the GetField method.

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

Example
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 System;
using System.Reflection;


 //Make two fields, one public and one read-only.
 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.Public|BindingFlags.Instance);
       Type MyTypeb = Type.GetType("Myfieldb");
       FieldInfo Myfieldinfob = MyTypeb.GetField("field",
          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.
       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
              			
            
See also:
FieldAttributes | Type.GetField | Type

Return to top


Property: IsLiteral (read-only)
Inherited
See base class member description: System.Reflection.FieldInfo.IsLiteral

Summary
Gets a value indicating whether the value is written at compile time and cannot be changed.
C# Syntax:
public bool IsLiteral {get;}
Remarks
The IsLiteral property is set when the FieldAttributes.Literal attribute is set. If this attribute is set, the field cannot be changed and is constant.
See also:
FieldAttributes

Return to top


Property: IsNotSerialized (read-only)
Inherited
See base class member description: System.Reflection.FieldInfo.IsNotSerialized

Summary
Gets a value indicating whether this field has the NotSerialized attribute.
C# Syntax:
public bool IsNotSerialized {get;}
Remarks
The IsNotSerialized property returns true when the field is marked with the FieldAttributes.NotSerialized flag. When this flag is set on a field, it indicates that the field does not have to be serialized when the type is remoted.
Example
using System;
using System.Reflection;
using System.Runtime.Serialization;

public class MyClass 
{
   public short myShort;

   // The following field will not be serialized.  
   [NonSerialized()]
   public int myInt;
}
public class Type_IsNotSerializable
{
   public static void Main()
   {  
      // Get the type of 'MyClass'.
      Type myType = typeof(MyClass);
 
      // Get the fields of 'MyClass'.
      FieldInfo[] myFields = myType.GetFields(BindingFlags.Public |
         BindingFlags.NonPublic |
         BindingFlags.Instance |
         BindingFlags.Static);
      Console.WriteLine("\nDisplaying if field is serializable\n");
      
      // Display whether the field is serializable or not.
      for(int i = 0; i < myFields.Length; i++)
         if(myFields[i].IsNotSerialized)
            Console.WriteLine("'{0}' field is not serializable", myFields[i]);
         else
            Console.WriteLine("'{0}' field is serializable", myFields[i]);
   }
}


    
See also:
FieldAttributes

Return to top


Property: IsPinvokeImpl (read-only)
Inherited
See base class member description: System.Reflection.FieldInfo.IsPinvokeImpl

Summary
Gets a value indicating whether the corresponding PinvokeImpl attribute is set in FieldAttributes.
C# Syntax:
public bool IsPinvokeImpl {get;}
Example
using System;
using System.Reflection;

public class Fieldinfo_IsPinvoke
{
   public string myField = "A public field";
   
   public static void Main()
   {
      Fieldinfo_IsPinvoke myObject = new Fieldinfo_IsPinvoke();
      
      //Get the Type and FieldInfo.
      Type myType1 = typeof(Fieldinfo_IsPinvoke);
      FieldInfo myFieldInfo = myType1.GetField("myField",
         BindingFlags.Public|BindingFlags.Instance);

      // Display the name, field and the PInvokeImpl attribute for the field.
      Console.Write("\n Name of Class: {0} ", myType1.FullName);
      Console.Write("\n Value of Field: {0}", myFieldInfo.GetValue(myObject));
      Console.Write("\n IsPinvokeImpl: {0} ", 
         myFieldInfo.IsPinvokeImpl );
   }
}

    
See also:
FieldAttributes

Return to top


Property: IsPrivate (read-only)
Inherited
See base class member description: System.Reflection.FieldInfo.IsPrivate

Summary
Gets a value indicating whether the field is private.
C# Syntax:
public bool IsPrivate {get;}
Remarks
Private fields are accessible only from member functions.

The IsPrivate property is set when the FieldAttributes.Private attribute is set.

To get the IsPrivate property, first get the class Type. From the Type, get the FieldInfo. From the FieldInfo, get the IsPrivate property. To access a non-public field, set the BindingFlags to NonPublic, and either Static or Instance in the GetField method.

Example
using System;
using System.Reflection;

class MyClass
{
   private string myField;
   public string[] myArray = new string[] {"New York", "New Jersey"};
   MyClass()
   {
	  myField = "Microsoft";
   }
   string GetField
   {
	   get
	   {
		   return myField;
	   }
   }
}

class FieldInfo_IsPrivate
{
   public static void Main()
   {
      try
      {
         // Gets the type of 'MyClass'.
         Type myType = typeof(MyClass);

         // Gets the field information of 'MyClass'.
         FieldInfo[] myFields = myType.GetFields(BindingFlags.NonPublic
            |BindingFlags.Public
            |BindingFlags.Instance);
      
         Console.WriteLine("\nDisplaying whether the fields of '{0}' are private or not:\n",myType);
         for(int i = 0; i < myFields.Length; i++)
         {
            // Check whether the field is private or not. 
            if(myFields[i].IsPrivate)
               Console.WriteLine("'{0}' is a private field", myFields[i].Name);
            else
               Console.WriteLine("'{0}' is not a private field", myFields[i].Name);
         }
      }
      catch(Exception e)
      {
         Console.WriteLine("Exception : {0} " , e.Message);
      }
   }
}

    
See also:
BindingFlags | Type

Return to top


Property: IsPublic (read-only)
Inherited
See base class member description: System.Reflection.FieldInfo.IsPublic

Summary
Gets a value indicating whether the field is public.
C# Syntax:
public bool IsPublic {get;}
Remarks
Public fields are accessible everywhere their corresponding classes are visible.

The IsPublic property is set when the FieldAttributes.Public attribute is set.

To get the IsPublic property, first get the class Type. From the Type, get the FieldInfo. From the FieldInfo, get the IsPublic property. If the field is other than public, it is protected and cannot be readily accessed. To access a not public field, set the BindingFlags to NonPublic, specify either BindingFlags.Instance or BindingFlags.Static, and use this for the GetField method.

Example

using System;
using System.Reflection;


 //Make two fields.
 public
 class Myfielda // private
 {
    private string SomeField = "private field";
    public string Field{
       get{return SomeField;}
    }
 }

 public
 class Myfieldb // public
 {
    public string SomeField = "public field";
    public string Field{
       get{return SomeField;}
    }
 }
 
 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("SomeField", BindingFlags.NonPublic|BindingFlags.Instance);
       Type MyTypeb = Type.GetType("Myfieldb");
       FieldInfo Myfieldinfob = MyTypeb.GetField("SomeField");
  
       //Get and Display the IsPublic and IsPrivate.
       Console.Write("\n{0}.", MyTypea.FullName);
       Console.Write("{0} - ", Myfieldinfoa.Name);
       Console.Write("{0};", Myfielda.Field);
       Console.Write("\n   IsPublic = {0}; ",Myfieldinfoa.IsPublic);
       Console.Write("\n   IsPrivate = {0}; ",Myfieldinfoa.IsPrivate);
  
       Console.Write("\n{0}.", MyTypeb.FullName);
       Console.Write("{0} - ", Myfieldinfob.Name);
       Console.Write("{0};", Myfieldb.Field);
       Console.Write("\n   IsPublic = {0}; ", Myfieldinfob.IsPublic);
       Console.Write("\n   IsPrivate = {0}; ",Myfieldinfob.IsPrivate);
  
       return 0;
    }
 }

    
This code produces the following output:

Reflection.FieldInfo

Myfielda.SomeField - private field;

IsPublic = False;

IsPrivate = True;

Myfieldb.SomeField - public field;

IsPublic = True;

IsPrivate = False;

See also:
FieldAttributes | BindingFlags

Return to top


Property: IsSpecialName (read-only)
Inherited
See base class member description: System.Reflection.FieldInfo.IsSpecialName

Summary
Gets a value indicating whether the corresponding SpecialName attribute is set in the FieldAttributes enumerator.
C# Syntax:
public bool IsSpecialName {get;}
Remarks
Names that begin with or contain an underscore character (_), property accessors, and operator overloading methods are examples of names that might require special treatment by some compilers.
Example
using System;
using System.Reflection;
using System.ComponentModel.Design;


class FieldInfo_IsSpecialName
{
   public static void Main()
   {     
      try
      {
         // Get the type handle of the 'ViewTechnology' class.
         Type myType = typeof(ViewTechnology);
         
         // Get the fields of the class 'ViewTechnology'.
         FieldInfo[] myField = myType.GetFields();

         Console.WriteLine("\nDisplaying fields that have 'SpecialName' attributes\n");
         for(int i = 0; i < myField.Length; i++)
         {
            // Check whether each field is a special name or not.
            if(myField[i].IsSpecialName)
            {
               Console.WriteLine("The field '{0}' has SpecialName attribute",
                  myField[i].Name);
            }
         }
      }
      catch(Exception e)
      {
         Console.WriteLine("Exception : {0} " , e.Message);
      }
   }
}

    
See also:
FieldAttributes

Return to top


Property: IsStatic (read-only)
Inherited
See base class member description: System.Reflection.FieldInfo.IsStatic

Summary
Gets a value indicating whether the field is static.
C# Syntax:
public bool IsStatic {get;}
Remarks
When a field is static, one copy of the field is shared by all instances of the type.

The IsStatic property is set when the FieldAttributes.Static attribute is set.

To get the IsStatic property, first get the class Type. From the Type, get the FieldInfo. From the FieldInfo, get the IsStatic property. To access a non-public field, set the BindingFlags to NonPublic in the GetField method and set the accessibility to Instance or Static.

Example

using System;
using System.Reflection;


 //Make two fields.
 public class Myfielda
 {
    private string field = "A private field";
    public string Field{
       get{return field;}
       set{if(field!=value){field=value;}}
    }
 }
 public class Myfieldb
 {
    static string field = "B static field";
    public string Field {
       get{return field;}
       set{if(field!=value){field=value;}}
    }
 }
  
 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|BindingFlags.Instance);
       Type MyTypeb = Type.GetType("Myfieldb");
       FieldInfo Myfieldinfob = MyTypeb.GetField("field", BindingFlags.NonPublic|BindingFlags.Static);
  
       //For the first field, get and display the name, field, and IsStatic.
       Console.Write("\n{0} - ", MyTypea.FullName);
       Console.Write("{0}; ", Myfieldinfoa.GetValue(Myfielda));
       Console.Write("IsStatic - {0}", Myfieldinfoa.IsStatic);
  
       //For the second field get and display the name, field, and IsStatic.
       Console.Write("\n{0} - ", MyTypeb.FullName);
       Console.Write("{0}; ", Myfieldinfob.GetValue(Myfieldb));
       Console.Write("IsStatic - {0}", Myfieldinfob.IsStatic);
  
       return 0;
    }
 }

    
This code produces the following output:

Reflection.FieldInfo

Myfielda - A private field; IsStatic - False

Myfieldb - B static field; IsStatic - True

See also:
FieldAttributes | Type.GetField | Type

Return to top


Property: MemberType (read-only)
Inherited
See base class member description: System.Reflection.FieldInfo.MemberType

Summary
Gets the Type of property reflected by this FieldInfo object. The retrieved value indicates that this member is a field.
C# Syntax:
public override MemberTypes MemberType {get;}
Remarks
This property is used when this field is being tested as a generic member.
Example
 using System;
 using System.Reflection;
 
 //Make a field 
 public class Myfield
 {
    private string field = "a private field";
    public string Field{
       get{return field;}
    }
 }
  
 public class Myfieldinfo
 {
    public static int Main()
    {
       Console.WriteLine ("\nReflection.FieldInfo");
       Myfield Myfield = new Myfield();
  
       //Get the Type and FieldInfo
       Type MyType = Type.GetType("Myfield");
       FieldInfo Myfieldinfo = MyType.GetField("field", BindingFlags.NonPublic|BindingFlags.Instance);
  
       //Get and Display the MemberType
       Console.Write ("\n{0}.", MyType.FullName);
       Console.Write ("{0} - ", Myfieldinfo.Name);
       Console.Write ("{0};", Myfield.Field);
  
       MemberTypes Mymembertypes = Myfieldinfo.MemberType;
       Console.Write(" MemberType is a {0}", Mymembertypes.ToString());
  
       return 0;
    }
 }

    
This code produces the following output:

Reflection.FieldInfo

Myfield.field - a private field; MemberType is a Field

See also:
FieldInfo | Type

Return to top


Overridden Property: Name (read-only)
Summary
Indicates the name of this field. This property is read-only.
C# Syntax:
public override string Name {get;}

Return to top


Overridden Property: ReflectedType (read-only)
Summary
Indicates the reference to the Type object from which this object was obtained. This property is read-only.
C# Syntax:
public override Type ReflectedType {get;}
Remarks
A FieldBuilder object represents a field of a particular class. In order to obtain a FieldBuilder object, the Type object that represents the class that supports the field is queried. This property holds a reference to that Type object.

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~FieldBuilder();

For more information on members inherited from System.Object click on the link above.

Return to top


Overloaded Method: GetCustomAttributes(
   bool inherit
)
Summary
Returns all the custom attributes defined for this field.
C# Syntax:
public override object[] GetCustomAttributes(
   bool inherit
);
Parameters:

inherit

Controls inheritance of custom attributes from base classes.

Return Value:
An array of type Object representing all the custom attributes of the constructor represented by this FieldBuilder instance.
Exceptions
Exception Type Condition
NotSupportedException This method is not supported.
Implements:
ICustomAttributeProvider.GetCustomAttributes

Return to top


Overloaded Method: GetCustomAttributes(
   Type attributeType,
   bool inherit
)
Summary
Returns all the custom attributes defined for this field identified by the given type.
C# Syntax:
public override object[] GetCustomAttributes(
   Type attributeType,
   bool inherit
);
Parameters:

attributeType

The custom attribute type.

inherit

Controls inheritance of custom attributes from base classes.

Return Value:
An array of type Object representing all the custom attributes of the constructor represented by this FieldBuilder instance.
Exceptions
Exception Type Condition
NotSupportedException This method is not supported.
Implements:
ICustomAttributeProvider.GetCustomAttributes

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetToken()
Summary
Returns the token representing this field.
C# Syntax:
public FieldToken GetToken();
Return Value:
Returns the FieldToken object that represents the token for this field.

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Overridden Method: GetValue(
   object obj
)
Summary
Retrieves the value of the field supported by the given object.
C# Syntax:
public override object GetValue(
   object obj
);
Parameters:

obj

The object on which to access the field.

Return Value:
An Object containing the value of the field reflected by this instance.
Exceptions
Exception Type Condition
NotSupportedException This method is not supported.
Remarks
If the field is static, the obj parameter is ignored. For non-static fields, obj should be an instance of a class that inherits or declares the field.

The return type of FieldBuilder.GetValue is Object. For example, if the field holds a Boolean primitive value, an instance of Object with the appropriate Boolean value is returned. Before returning the value, FieldBuilder.GetValue checks to see if the user has access permission.

Access restrictions are ignored for fully-trusted code.Private constructors, methods, fields, and properties can be accessed and invoked using Reflection whenever the code is fully-trusted.

Return to top


Method: GetValueDirect(
   TypedReference obj
)
Inherited
See base class member description: System.Reflection.FieldInfo.GetValueDirect

Summary
Returns the value of a field supported by a given object.
This member is not CLS Compliant

C# Syntax:
[CLSCompliant(false)]
public virtual object GetValueDirect(
   TypedReference obj
);
Parameters:

obj

A managed pointer to a location and a runtime representation of the type that might be stored at that location.

Return Value:
An Object containing a field value.
Exceptions
Exception Type Condition
NotSupportedException The caller requires the CLS alternative, but called this method instead.

Return to top


Overridden Method: IsDefined(
   Type attributeType,
   bool inherit
)
Summary
Indicates whether an attribute having the specified type is defined on a field.
C# Syntax:
public override bool IsDefined(
   Type attributeType,
   bool inherit
);
Parameters:

attributeType

The type of the attribute.

inherit

Controls inheritance of custom attributes from base classes.

Return Value:
true if one or more instance of attributeType is defined on this field; otherwise, false.
Exceptions
Exception Type Condition
NotSupportedException This method is not currently supported. Retrieve the field using Type.GetField and call MemberInfo.IsDefined on the returned FieldInfo.
Implements:
ICustomAttributeProvider.IsDefined

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: SetConstant(
   object defaultValue
)
Summary
Sets the default value of this field.
C# Syntax:
public void SetConstant(
   object defaultValue
);
Parameters:

defaultValue

The new default value for this field.

Exceptions
Exception Type Condition
InvalidOperationException The containing type has been created using TypeBuilder.CreateType.
Remarks
defaultValue is restricted to the following types: Boolean, SByte, Int16, Int32, Int64, Byte, UInt16, UInt32, UInt64, Single, Double, DateTime, Char, String, and Enum. If the type of the field is Decimal or Object, defaultValue can only be null.

Return to top


Overloaded Method: SetCustomAttribute(
   CustomAttributeBuilder customBuilder
)
Summary
Sets a custom attribute using a custom attribute builder.
C# Syntax:
public void SetCustomAttribute(
   CustomAttributeBuilder customBuilder
);
Parameters:

customBuilder

An instance of a helper class to define the custom attribute.

Exceptions
Exception Type Condition
ArgumentNullException con is null.
InvalidOperationException The parent type of this field is complete.

Return to top


Overloaded Method: SetCustomAttribute(
   ConstructorInfo con,
   byte[] binaryAttribute
)
Summary
Sets a custom attribute using a specified custom attribute blob.
C# Syntax:
public void SetCustomAttribute(
   ConstructorInfo con,
   byte[] binaryAttribute
);
Parameters:

con

The constructor for the custom attribute.

binaryAttribute

A byte blob representing the attributes.

Exceptions
Exception Type Condition
ArgumentNullException con or binaryAttribute is null.
InvalidOperationException The parent type of this field is complete.
Remarks
See the metadata specification for details on how to format binaryAttribute.

Return to top


Method: SetMarshal(
   UnmanagedMarshal unmanagedMarshal
)
Summary
Describes the native marshaling of the field.
C# Syntax:
public void SetMarshal(
   UnmanagedMarshal unmanagedMarshal
);
Parameters:

unmanagedMarshal

A descriptor specifying the native marshalling of this field.

Exceptions
Exception Type Condition
ArgumentNullException unmanagedMarshal is null.
InvalidOperationException The containing type has been created using TypeBuilder.CreateType.

Return to top


Method: SetOffset(
   int iOffset
)
Summary
Specifies the field layout.
C# Syntax:
public void SetOffset(
   int iOffset
);
Parameters:

iOffset

The offset of the field within the type containing this field.

Exceptions
Exception Type Condition
InvalidOperationException The containing type has been created using TypeBuilder.CreateType.

Return to top


Overloaded Method: SetValue(
   object obj,
   object value
)
Inherited
See base class member description: System.Reflection.FieldInfo.SetValue

Summary
Sets the value of the field supported by the given object.
C# Syntax:
public void SetValue(
   object obj,
   object value
);
Parameters:

obj

The object whose field value will be set.

value

The value to assign to the field.

Exceptions
Exception Type Condition
FieldAccessException The caller does not have permission to access this field.
TargetException The obj parameter is null and the field is an instance field.
ArgumentException The field does not exist on the object.

-or-

The value parameter cannot be converted and stored in the field.

Remarks
This method will assign value to the field reflected by this instance on object obj. If the field is static, obj will be ignored. For non-static fields, obj should be an instance of a class that inherits or declares the field. The new value is passed as an Object. For example, if the field's type is Boolean, an instance of Object with the appropriate Boolean value is passed. Before setting the value, SetValue checks to see if the user has access permission. This final method is a convenience method for calling the following SetValue method.

Note Access restrictions are ignored for fully trusted code. That is, private constructors, methods, fields, and properties can be accessed and invoked using reflection whenever the code is fully trusted.
Example

using System;
using System.Reflection;
using System.Globalization;

public class MyClass
{
   private string myString;
   public MyClass()
   {
      myString = "Old value";
   }
   string GetField
   {
	  get
	  {
		  return myString;
	  }
   }
}

public class FieldInfo_SetValue
{
   public static void Main()
   {
      try
      {
         MyClass myObject = new MyClass();
         Type myType = Type.GetType("MyClass");
	
         FieldInfo myFieldInfo = myType.GetField("myString", 
            BindingFlags.NonPublic |
            BindingFlags.Instance); 

         // Display string before applying 'Set Value' on the field.
         Console.WriteLine( "\nField value of 'myString': {0}", myFieldInfo.GetValue( myObject ) ); 
          
         // Display 'SetValue' signature used to set the value of a field.
         Console.WriteLine( "Applying 'SetValue( Object,Object )' method");    

         // Change field value using 'SetValue' method. 
         myFieldInfo.SetValue( myObject , "New value"); 
         // Display string after applying 'Set Value' on the field.
         Console.WriteLine( "Field value of 'mystring' : {0}", myFieldInfo.GetValue( myObject )  );
			
         // Set field value using 'SetValue' method to its old value. 
         myFieldInfo.SetValue( myObject , "Old value" ); 

         myFieldInfo = myType.GetField("myString", 
            BindingFlags.NonPublic | 
            BindingFlags.Instance); 

         // Display string before applying 'SetValue' on the field.
         Console.Write( "\nField value of 'mystring' : {0}\n", myFieldInfo.GetValue( myObject ) ); 
	
         // Display 'SetValue' signature used to set value of a field.
         Console.WriteLine( "Applying 'SetValue( Object,Object,BindingFlags,Binder,CultureInfo )' method"); 

         // Change field value using 'SetValue' method. 
         myFieldInfo.SetValue( myObject, "New value", 
            BindingFlags.Default, null , null ); 	
         // Display string after applying 'SetValue' on the field.
         Console.WriteLine( "Field value of 'mystring' : {0}", myFieldInfo.GetValue( myObject )  );

      }
      catch( Exception e )
      {
         // Any exception generated is displayed. 
         Console.WriteLine( "Exception: {0}", e.Message );
      }
   }
}

    
.NET Framework Security:
ReflectionPermission for returning fields that are not public. Associated enumeration: ReflectionPermissionFlag.MemberAccess

Return to top


Overloaded Method: SetValue(
   object obj,
   object val,
   BindingFlags invokeAttr,
   Binder binder,
   CultureInfo culture
)
Summary
Sets the value of the field supported by the given object.
C# Syntax:
public override void SetValue(
   object obj,
   object val,
   BindingFlags invokeAttr,
   Binder binder,
   CultureInfo culture
);
Parameters:

obj

The object on which to access the field.

val

The value to assign to the field.

invokeAttr

A member of IBinder that specifies the type of binding that is desired (for example, IBinder.CreateInstance, IBinder.ExactBinding).

binder

A set of properties and enabling for binding, coercion of argument types, and invocation of members using reflection. If binder is null, then IBinder.DefaultBinding is used.

culture

The software preferences of a particular culture.

Exceptions
Exception Type Condition
NotSupportedException This method is not supported.
Remarks
This method will assign the val parameter to the field reflected by this instance on Objectobj. If the field is static, obj will be ignored. For non-static fields, obj should be an instance of a class that inherits or declares the field.

The new value is passed as an Object. For example, if the field's type is Boolean, an instance of Object with the appropriate Boolean value is passed. Before setting the value, FieldBuilder.SetValue checks to see if the user has access permission.

Access restrictions are ignored for fully-trusted code.Private constructors, methods, fields, and properties can be accessed and invoked using Reflection whenever the code is fully-trusted.

This method is currently not supported. As a workaround, retrieve the FieldInfo by reflecting on the finished type and call FieldInfo.SetValue to set the value of the field.

Return to top


Method: SetValueDirect(
   TypedReference obj,
   object value
)
Inherited
See base class member description: System.Reflection.FieldInfo.SetValueDirect

Summary
Sets the value of the field supported by the given object.
This member is not CLS Compliant

C# Syntax:
[CLSCompliant(false)]
public virtual void SetValueDirect(
   TypedReference obj,
   object value
);
Parameters:

obj

A managed pointer to a location and a runtime representation of the type that can be stored at that location.

value

The value to assign to the field.

Exceptions
Exception Type Condition
NotSupportedException The caller requires the CLS alternative, but called this method instead.

Return to top


Method: ToString()
Inherited
See base class member description: System.Object.ToString
C# Syntax:
public virtual string ToString();

For more information on members inherited from System.Object click on the link above.

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.