System.Reflection.FieldInfo Class

Assembly: Mscorlib.dll
Namespace: System.Reflection
Summary
Discovers the attributes of a field and provides access to field metadata.
C# Syntax:
[Serializable]
public abstract class FieldInfo : MemberInfo
Remarks
The field information is obtained from metadata.FieldInfo does not have a public constructor.FieldInfo objects are obtained by calling either the Type.GetFields or Type.GetField method of a Type object.

Fields are variables defined in the class.FieldInfo provides access to the metadata for a field within a class and provides dynamic set and get functionality for the field. The class is not loaded into memory until invoke or get is called on the object.



Notes to inheritors: When you inherit from FieldInfo, you must override the following members: FieldInfo.GetValue and FieldInfo.SetValue.
Example
using System;
using System.Reflection;

public class FieldInfoClass
{
   public int myField1 = 0;
   protected string myField2 = null;
   public static void Main()
   {
      FieldInfo[] myFieldInfo;
      Type myType = typeof(FieldInfoClass);
      // Get the type and fields of 'FieldInfoClass' class.
      myFieldInfo = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance
                                      | BindingFlags.Public);
      Console.WriteLine("\nThe fields related to " + 
                           "'FieldInfoClass' class are \n");
      // Print the properties of 'FieldInfoClass' class.
      for(int i = 0; i < myFieldInfo.Length; i++)
      {
         Console.WriteLine("\nName            : {0}", myFieldInfo[i].Name);
         Console.WriteLine("Declaring Type  : {0}", myFieldInfo[i].DeclaringType);
         Console.WriteLine("IsPublic        : {0}", myFieldInfo[i].IsPublic);
         Console.WriteLine("MemberType      : {0}", myFieldInfo[i].MemberType);
         Console.WriteLine("FieldType       : {0}", myFieldInfo[i].FieldType);
         Console.WriteLine("IsFamily        : {0}", myFieldInfo[i].IsFamily);
      }
   }
}

    
See also:
System.Reflection Namespace | Type

System.Reflection.FieldInfo Member List:

Public Properties
Attributes Read-only

Gets the attributes associated with this field.
DeclaringType
(inherited from System.Reflection.MemberInfo)
Read-only

See base class member description: System.Reflection.MemberInfo.DeclaringType


Gets the class that declares this member.
FieldHandle Read-only

Gets a RuntimeFieldHandle, which is a handle to the internal metadata representation of a field.
FieldType Read-only

Gets the type of this field object.
IsAssembly Read-only

Gets a value indicating whether this field has Assembly level visibility.
IsFamily Read-only

Gets a value indicating whether this field has Family level visibility.
IsFamilyAndAssembly Read-only

Gets a value indicating whether this field has FamilyAndAssembly level visibility.
IsFamilyOrAssembly Read-only

Gets a value indicating whether this field has FamilyOrAssembly level visibility.
IsInitOnly Read-only

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

Gets a value indicating whether the value is written at compile time and cannot be changed.
IsNotSerialized Read-only

Gets a value indicating whether this field has the NotSerialized attribute.
IsPinvokeImpl Read-only

Gets a value indicating whether the corresponding PinvokeImpl attribute is set in FieldAttributes.
IsPrivate Read-only

Gets a value indicating whether the field is private.
IsPublic Read-only

Gets a value indicating whether the field is public.
IsSpecialName Read-only

Gets a value indicating whether the corresponding SpecialName attribute is set in the FieldAttributes enumerator.
IsStatic Read-only

Gets a value indicating whether the field is static.
MemberType Read-only

Overridden:
Gets the Type of property reflected by this FieldInfo object. The retrieved value indicates that this member is a field.
Name
(inherited from System.Reflection.MemberInfo)
Read-only

See base class member description: System.Reflection.MemberInfo.Name


Gets the name of this member.
ReflectedType
(inherited from System.Reflection.MemberInfo)
Read-only

See base class member description: System.Reflection.MemberInfo.ReflectedType


Gets the class object that was used to obtain this instance of MemberInfo.
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
(inherited from System.Reflection.MemberInfo)
Overloaded:
GetCustomAttributes(bool inherit)

See base class member description: System.Reflection.MemberInfo.GetCustomAttributes


When overridden in a derived class, returns an array of all of the custom attributes.
GetCustomAttributes
(inherited from System.Reflection.MemberInfo)
Overloaded:
GetCustomAttributes(Type attributeType, bool inherit)

See base class member description: System.Reflection.MemberInfo.GetCustomAttributes


When overridden in a derived class, returns an array of custom attributes identified by Type.
GetFieldFromHandle Gets a FieldInfo containing the value of the field reflected by this instance.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
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 When overridden in a derived class, returns the value of a field supported by a given object.
GetValueDirect Returns the value of a field supported by a given object.
IsDefined
(inherited from System.Reflection.MemberInfo)
See base class member description: System.Reflection.MemberInfo.IsDefined


When overridden in a derived class, indicates whether one or more instance of attributeType is defined on this member.
SetValue Overloaded:
SetValue(object obj, object value)

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

When overridden in a derived class, sets the value of the field supported by the given object.
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 Constructors
ctor #1 Default constructor. This constructor is called by derived class constructors to initialize state in this type.
Initializes a new instance of the FieldInfo class.
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.FieldInfo Member Details

ctor #1
Summary
Initializes a new instance of the FieldInfo class.

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
C# Syntax:
protected FieldInfo();

Return to top


Property: Attributes (read-only)
Summary
Gets the attributes associated with this field.
C# Syntax:
public abstract FieldAttributes Attributes {get;}
Remarks
All members have a set of attributes, which are defined in relation to the specific type of member.FieldAttributes informs the user whether this field is the private field, a static field, and so on.

To get the Attributes property, first get the class Type. From the Type, get the FieldInfo. From the FieldInfo, get the Attributes.

See also:
FieldAttributes | Type

Return to top


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

Summary
Gets the class that declares this member.
C# Syntax:
public abstract Type DeclaringType {get;}
Remarks
The DeclaringType property retrieves a reference to the Type object for the type that declares this member. A member of a class (or interface) is either declared or inherited from a base class (or interface). The returned class might not be the same as the Type object used to obtain this MemberInfo object.
Example
The following example shows how DeclaringType works with classes and interfaces.

 interface i {
 int MyVar() ;
 };
 // DeclaringType for MyVar is i.
 
 class A : i {
 public int MyVar() { return 0; }
 };
 // DeclaringType for MyVar is A.
 
 class B : A {
 new int MyVar() { return 0; }
 };
 // DeclaringType for MyVar is B.
 
 class C : A {
 };
 // DeclaringType for MyVar is A.

    

The following example uses DeclaringType to retrieve the member names of the System.IO.BufferedStream class, along with the class in which those members are declared.

 using System;
 using System.IO;
 using System.Reflection;
 
 class Mymemberinfo { 
 
   public static void Main(string[] args) { 
 
    Console.WriteLine ("\nReflection.MemberInfo");
 
    //Get the Type and MemberInfo. 
    Type MyType =Type.GetType("System.IO.BufferedStream");
    MemberInfo[] Mymemberinfoarray = MyType.GetMembers();
 
    //Get and display the DeclaringType method. 
    Console.Write("\nThere are {0} members in ", Mymemberinfoarray.Length); 
    Console.Write("{0}.", MyType.FullName); 
 
    foreach (MemberInfo Mymemberinfo in Mymemberinfoarray) {  
      Console.Write("\n" + Mymemberinfo.Name + " declaring type - "
        + Mymemberinfo.DeclaringType); 
    }
   }
 }

    

This code produces the following output:

Reflection.MemberInfo

There are 31 members in System.IO.BufferedStream.

WriteByte declaring type - System.IO.BufferedStream

Write declaring type - System.IO.BufferedStream

ReadByte declaring type - System.IO.BufferedStream

Read declaring type - System.IO.BufferedStream

SetLength declaring type - System.IO.BufferedStream

Seek declaring type - System.IO.BufferedStream

EndWrite declaring type - System.IO.Stream

BeginWrite declaring type - System.IO.Stream

EndRead declaring type - System.IO.Stream

BeginRead declaring type - System.IO.Stream

Flush declaring type - System.IO.BufferedStream

Close declaring type - System.IO.BufferedStream

set_Position declaring type - System.IO.BufferedStream

get_Position declaring type - System.IO.BufferedStream

get_Length declaring type - System.IO.BufferedStream

get_CanWrite declaring type - System.IO.BufferedStream

get_CanSeek declaring type - System.IO.BufferedStream

get_CanRead declaring type - System.IO.BufferedStream

InitializeLifetimeService declaring type - System.MarshalByRefObject

GetHashCode declaring type - System.Object

Equals declaring type - System.Object

ToString declaring type - System.Object

GetLifetimeService declaring type - System.MarshalByRefObject

GetType declaring type - System.Object

.ctor declaring type - System.IO.BufferedStream

.ctor declaring type - System.IO.BufferedStream

CanRead declaring type - System.IO.BufferedStream

CanWrite declaring type - System.IO.BufferedStream

CanSeek declaring type - System.IO.BufferedStream

Length declaring type - System.IO.BufferedStream

Position declaring type - System.IO.BufferedStream



Note DeclaringType returns only the member names and the names of their declaring types. To return the member names with their prototypes, call MemberInfo.ToString.

In the following code example, when B overrides virtual method M from A, it essentially redefines (or redeclares) this method. Therefore, B.M's MethodInfo reports the declaring type as B rather than A, even though A is where this method was originally declared.

class A {
    virtual public void M () {}
}
class B: A {
    override public void M () {}
}

    

Return to top


Property: FieldHandle (read-only)
Summary
Gets a RuntimeFieldHandle, which is a handle to the internal metadata representation of a field.
C# Syntax:
public abstract RuntimeFieldHandle FieldHandle {get;}
Remarks
The handles are valid only in the appdomain in which they were obtained.
Example
using System;
using System.Reflection;
  
public class MyClass
{
   public string MyField = "Microsoft";
}

public class FieldInfo_FieldHandle
{
   public static void Main()
   {
    
      MyClass myClass =new MyClass();

      // Get the type of the class 'MyClass'.
      Type myType = typeof(MyClass);

      try
      {
         // Get the field information of 'MyField' in 'MyClass'.
         FieldInfo myFieldInfo = myType.GetField("MyField", BindingFlags.Public 
            | BindingFlags.Instance);
      
         // Check whether the fieldInfo object is null or not.
         if(myFieldInfo!=null)
         {
            // Get the handle for the field.
            RuntimeFieldHandle myFieldHandle=myFieldInfo.FieldHandle;

            DisplayFieldHandle(myFieldHandle);
         }
         else
         {
            Console.WriteLine("The 'myFieldInfo' object is null");
         }
      }  
      catch(Exception e)
      {
         Console.WriteLine(" Exception : {0}", e.Message);
      }
   }

   public static void DisplayFieldHandle(RuntimeFieldHandle myFieldHandle)
   {
      // Get the type from the handle.
      FieldInfo myField = FieldInfo.GetFieldFromHandle(myFieldHandle);      
      
      // Display the type.
      Console.WriteLine("\nDisplaying the field from the handle.\n");
      Console.WriteLine("The type is : '{0}' ", myField.ToString());
   }
}

    

Return to top


Property: FieldType (read-only)
Summary
Gets the type of this field object.
C# Syntax:
public abstract Type FieldType {get;}
Remarks
The type is some primitive data type, such as String, Boolean, or GUID.

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

Example

 //Make a field
 public class Myfield
 {
    private string field = "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.Instance|BindingFlags.NonPublic);
  
       //Get and Display the FieldType
       Console.Write ("\n{0}.", MyType.FullName);
       Console.Write ("{0} - ", Myfieldinfo.Name);
       Console.Write ("{0};", Myfield.Field);
       Console.Write ("\nFieldType = {0}", Myfieldinfo.FieldType);
  
       return 0;
    }
 }

    
This code produces the following output:
              				Reflection.FieldInfo
              				Myfield.field - private field;
              				FieldType = System.String
              			
            
See also:
FieldAttributes | Type

Return to top


Property: IsAssembly (read-only)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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


Overridden Property: MemberType (read-only)
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


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

Summary
Gets the name of this member.
C# Syntax:
public abstract string Name {get;}
Remarks
Only the simple name is returned, not the fully qualified name. For example, for a member System.Reflection.MemberTypes.Field, the Name property would be Field.

To get the Name property, get the class Type. From the Type, get the MemberInfo array. From a MemberInfo element of the array, obtain the Name property.

Example
This example lists the Name and DeclaringType property of each member of the System.Empty class.
using System;
using System.Reflection;
 
class Mymemberinfo
 {
    public static int Main()
    {
       Console.WriteLine ("\nReflection.MemberInfo");
       
       //Get the Type and MemberInfo.
       Type MyType = Type.GetType("System.Empty");
       MemberInfo[] Mymemberinfoarray = MyType.GetMembers();
  
       //Get and display the DeclaringType method.
       Console.Write("\nThere are {0} members in ",
          Mymemberinfoarray.GetLength(0));
       Console.Write("{0}.", MyType.FullName);
  
       foreach (MemberInfo Mymemberinfo in Mymemberinfoarray)
       {
          Console.Write("\n" + Mymemberinfo.Name
             + " declaring type - " +
              Mymemberinfo.DeclaringType);
       }
  
       return 0;
    }
 }
 /*
 This code produces the following output:

Reflection.MemberInfo

There are 6 members in System.Empty.
Value declaring type - System.Empty
GetObjectData declaring type - System.Empty
GetHashCode declaring type - System.Object
Equals declaring type - System.Object
ToString declaring type - System.Empty
GetType declaring type - System.Object
 */

    

Return to top


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

Summary
Gets the class object that was used to obtain this instance of MemberInfo.
C# Syntax:
public abstract Type ReflectedType {get;}
Remarks
The ReflectedType property retrieves the Type object that was used to obtain this instance of MemberInfo. A MemberInfo object represents a member of a particular class or interface.

In order to obtain a MethodInfo object:

Example
 using System;
 using System.IO;
 using System.Reflection;
 
 class Mymemberinfo { 
 
   public static void Main(string[] args) { 
 
    Console.WriteLine ("\nReflection.MemberInfo");
 
    //Get the Type and MemberInfo  
    Type MyType =Type.GetType("System.IO.BufferedStream"); 
    MemberInfo[] Mymemberinfoarray = MyType.GetMembers(); 
 
    //Get and display the DeclaringType method 
    Console.Write("\nThere are {0} members in ", Mymemberinfoarray.Length); 
    Console.Write("{0}.", MyType.FullName); 
 
    foreach (MemberInfo Mymemberinfo in Mymemberinfoarray) { 
      Console.Write("\n" + Mymemberinfo.Name + " reflected type - " +
         Mymemberinfo.ReflectedType);
    }
   }
 }

    
This code produces the following output:

Reflection.MemberInfo

There are 31 members in System.IO.BufferedStream.

WriteByte reflected type - System.IO.BufferedStream

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:
~FieldInfo();

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

Return to top


Overloaded Method: GetCustomAttributes(
   bool inherit
)
Inherited
See base class member description: System.Reflection.MemberInfo.GetCustomAttributes

Summary
When overridden in a derived class, returns an array of all of the custom attributes.
C# Syntax:
public abstract object[] GetCustomAttributes(
   bool inherit
);
Parameters:

inherit

Specifies whether to search this member's inheritance chain to find the attributes.

Return Value:
An array of all the custom attributes, or an array with zero elements if no attributes are defined.
Implements:
ICustomAttributeProvider.GetCustomAttributes
Example

using System;
using System.Reflection;

// Define a custom attribute with one named parameter.
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
   private string myName;
   public MyAttribute(string name)
   {
      myName = name;
   }
   public string Name
   {
      get
      {
         return myName;
      }
   }
}

// Define a class which has the custom attribute associated with one of its members.
public class MyClass1
{
   [MyAttribute("This is an example attribute")]
   public void MyMethod(int i)
   {
      return;
   }
}

public class MemberInfo_GetCustomAttributes
{
   public static void Main()
   {
      try
      {
         // Get the type of the class 'MyClass1'.
         Type myType = typeof(MyClass1);
         // Get the members associated with the class 'MyClass1'.
         MemberInfo[] myMembers = myType.GetMembers();

         // Display the attributes for each of the members of the class 'MyClass1'.
         for(int i = 0; i < myMembers.Length; i++)
         {
            Object[] myAttributes = myMembers[i].GetCustomAttributes(false);
            if(myAttributes.Length > 0)
            {
               Console.WriteLine("\nThe attributes for the member {0} are : \n", myMembers[i]);
               for(int j = 0; j < myAttributes.Length; j++)
                  Console.WriteLine("The type of the attribute is : {0}", myAttributes[j]);
            }
         }
      }
      catch(Exception e)
      {
         Console.WriteLine("Exception Caught! "+e.Message);
      }
   }
}

    
See also:
Object | CustomAttributeBuilder

Return to top


Overloaded Method: GetCustomAttributes(
   Type attributeType,
   bool inherit
)
Inherited
See base class member description: System.Reflection.MemberInfo.GetCustomAttributes

Summary
When overridden in a derived class, returns an array of custom attributes identified by Type.
C# Syntax:
public abstract object[] GetCustomAttributes(
   Type attributeType,
   bool inherit
);
Parameters:

attributeType

The type of attribute to search for. Only attributes that are assignable to this type are returned.

inherit

Specifies whether to search this member's inheritance chain to find the attributes.

Return Value:
An array of custom attributes defined on this reflected member, or an array with zero (0) elements if no attributes are defined.
Exceptions
Exception Type Condition
TypeLoadException If the custom attribute type can not be loaded.
Implements:
ICustomAttributeProvider.GetCustomAttributes

Return to top


Method: GetFieldFromHandle(
   RuntimeFieldHandle handle
)
Summary
Gets a FieldInfo containing the value of the field reflected by this instance.
C# Syntax:
public static FieldInfo GetFieldFromHandle(
   RuntimeFieldHandle handle
);
Parameters:

handle

A handle to the internal metadata representation of a field.

Return Value:
A FieldInfo containing the value of the field reflected by this instance.
Remarks
The handles are valid only in the application domain in which they were obtained.
Example
using System;
using System.Reflection;

public class FieldInfo_GetFieldFromHandle
{
   public string x;
   public char y;
   public float a;
   public int b;

   public static void Main()
   {
      // Get the type of 'FieldInfo_GetFieldFromHandle' class.
      Type myType = typeof(FieldInfo_GetFieldFromHandle);
      // Get the fields of 'FieldInfo_GetFieldFromHandle' class.
      FieldInfo [] myFieldInfoArray = myType.GetFields();
      Console.WriteLine("\nThe field information of the declared" +
                         " fields x, y, a, b:\n");
      RuntimeFieldHandle myRuntimeFieldHandle;
      for(int i = 0; i < myFieldInfoArray.Length; i++)
      {
         // Get the RuntimeFieldHandle of the 'myFieldInfoArray'.
         myRuntimeFieldHandle = myFieldInfoArray[i].FieldHandle;
         // Call the 'GetFieldFromHandle' method. 
         FieldInfo myFieldInfo = FieldInfo.GetFieldFromHandle(myRuntimeFieldHandle);
         // Print the Field information of 'myFieldInfo'.
         Console.WriteLine("{0}", myFieldInfo);
      }
   }
}

    

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: 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


Method: GetValue(
   object obj
)
Summary
When overridden in a derived class, returns the value of a field supported by a given object.
C# Syntax:
public abstract object GetValue(
   object obj
);
Parameters:

obj

The object whose field value will be returned.

Return Value:
An object containing the value of the field reflected by this instance.
Exceptions
Exception Type Condition
TargetException The field is non-static and obj is null.
NotSupportedException A field is marked literal, but the field does not have one of the accepted literal types.
FieldAccessException The caller does not have permission to access this field.
ArgumentException The method is neither declared nor inherited by the class of obj.
Remarks
If the field is static, obj is ignored. For non-static fields, obj should be an instance of a class that inherits or declares the field. Note that the return type of 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, GetValue checks to see if the user has access permission.

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

using System;
using System.Reflection;

public class MyClass
{
   public string myFieldA;
   public string myFieldB; 
   public MyClass()
   {
     myFieldA = "A public field";
	  myFieldB = "Another public field";
   }
}

public class FieldInfo_GetValue
{
	public static void Main()
	{
      MyClass myInstance = new MyClass();
      // Get the type of the class MyClass.
      Type myType = typeof(MyClass);
      try
      {
         // Get the FieldInfo of the class MyClass.
         FieldInfo[] myFields = myType.GetFields(BindingFlags.Public 
            | BindingFlags.Instance);
         // Display the values of the fields to the console.
         Console.WriteLine("\nDisplaying the values of the fields of '{0}' class\n",
            myType);
         for(int i = 0; i < myFields.Length; i++)
         {
            Console.WriteLine("The value of the field '{0}' is : {1}",
            	myFields[i].Name, myFields[i].GetValue(myInstance));
         }
      }  
      catch(FieldAccessException e)
      {
         Console.WriteLine("FieldAccessException : {0}", e.Message);
      }
      catch(TargetException e)
      {
         Console.WriteLine("TargetException : {0}", e.Message);
      }
      catch(ExecutionEngineException e)
      {
         Console.WriteLine("ExecutionEngineException : {0}", e.Message);
      }
      catch(MemberAccessException e)
      {
         Console.WriteLine("MemberAccessException : {0}", e.Message);
      }
      catch(Exception e)
      {
         Console.WriteLine("Exception : {0}", e.Message);
      }
   }
}

    
See also:
Object

Return to top


Method: GetValueDirect(
   TypedReference obj
)
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


Method: IsDefined(
   Type attributeType,
   bool inherit
)
Inherited
See base class member description: System.Reflection.MemberInfo.IsDefined

Summary
When overridden in a derived class, indicates whether one or more instance of attributeType is defined on this member.
C# Syntax:
public abstract bool IsDefined(
   Type attributeType,
   bool inherit
);
Parameters:

attributeType

The Type object to which the custom attributes are applied.

inherit

Specifies whether to search this member's inheritance chain to find the attributes.

Return Value:
true if one or more instance of attributeType is defined on this member; otherwise false.
Implements:
ICustomAttributeProvider.IsDefined
Example

using System;
using System.Reflection;

// Define a custom attribute with one named parameter.
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
   private string myName;
   public MyAttribute(string name)
   {
      myName = name;
   }
   public string Name
   {
      get
      {
         return myName;
      }
   }
}

// Define a class which has the custom attribute associated with one of its members.
public class MyClass1
{
   [MyAttribute("This is an example attribute")]
   public void MyMethod(int i)
   {
      return;
   }
}

public class MemberInfo_GetCustomAttributes_IsDefined
{
   public static void Main()
   {
      try
      {
         // Get the type of the class 'MyClass1'.
         Type myType = typeof(MyClass1);
         // Get the members associated with the class 'MyClass1'.
         MemberInfo[] myMembers = myType.GetMembers();

         // Display the attributes for each of the members of the class 'MyClass1'.
         for(int i = 0; i < myMembers.Length; i++)
         {
            // Display the attribute if it is of type 'MyAttribute'.
            if(myMembers[i].IsDefined(typeof(MyAttribute), false))
            {
               Object[] myAttributes = myMembers[i].GetCustomAttributes(typeof(MyAttribute), false);
               Console.WriteLine("\nThe attributes of type 'MyAttribute' for the member {0} are : \n",
                                    myMembers[i]);
               for(int j = 0; j < myAttributes.Length; j++)
                  // Display the value associated with the attribute.
                  Console.WriteLine("The value of the attribute is : \"{0}\"",
                                       ((MyAttribute)myAttributes[j]).Name);
            }
         }
      }
      catch(Exception e)
      {
         Console.WriteLine("Exception Caught! "+e.Message);
      }
   }
}

    

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


Overloaded Method: SetValue(
   object obj,
   object value
)
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 value,
   BindingFlags invokeAttr,
   Binder binder,
   CultureInfo culture
)
Summary
When overridden in a derived class, sets the value of the field supported by the given object.
C# Syntax:
public abstract void SetValue(
   object obj,
   object value,
   BindingFlags invokeAttr,
   Binder binder,
   CultureInfo culture
);
Parameters:

obj

The object whose field value will be set.

value

The value to assign to the field.

invokeAttr

A field of Binder that specifies the type of binding that is desired (for example, Binder.CreateInstance or Binder.ExactBinding).

binder

A set of properties that enables the binding, coercion of argument types, and invocation of members through reflection. If binder is null, then Binder.DefaultBinding is used.

culture

The software preferences of a particular culture.

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

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


Method: SetValueDirect(
   TypedReference obj,
   object value
)
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.