Field Attributes

In this chapter you will learn:

  1. How to access Field Attributes

Access Field Attributes

FieldInfo.Attributes Property gets the attributes associated with this field.

using System;/*  j a va2 s  .c o  m*/
using System.Reflection;

public class Demo
{
    private string m_field = "String A";
    public string Field = "String B";
    public const string FieldC = "String C";
}

public class Myfieldattributes
{
    public static void Main()
    {
        Demo d = new Demo();
        Type myType = typeof(Demo);
        FieldInfo fiPrivate = myType.GetField("m_field",BindingFlags.NonPublic | BindingFlags.Instance);
        DisplayField(d, fiPrivate);

        FieldInfo fiPublic = myType.GetField("Field",BindingFlags.Public | BindingFlags.Instance);
        DisplayField(d, fiPublic);

        FieldInfo fiConstant = myType.GetField("FieldC",BindingFlags.Public | BindingFlags.Static);
        DisplayField(d, fiConstant);
    }

    static void DisplayField(Object obj, FieldInfo f)
    { 
        Console.WriteLine("{0} = \"{1}\"; attributes: {2}", f.Name, f.GetValue(obj), f.Attributes);
    }
}

Next chapter...

What you will learn in the next chapter:

  1. How to get FieldHandle
  2. Get Field From Field Handle
Home » C# Tutorial » Reflection
Reflection
Type
Type properties
Field reflection
Field Type
Field Attributes
FieldHandle
Field value
Set Field value
delegate reflection
Event reflection
Indexer reflection
Properties Reflection
Method
Parameter
Invoke
Type Instantiating
interface reflection
Generic type reflection
Reflection on nested Types
Subtype
Array reflection
Assembly