Check if a field is private in CSharp

Description

The following code shows how to check if a field is private.

Example


/*from  w w w .  j a va 2 s  . c o m*/
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()
    {
        Type myType = typeof(MyClass);
        FieldInfo[] myFields = myType.GetFields(BindingFlags.NonPublic
            |BindingFlags.Public
            |BindingFlags.Instance);

        for(int i = 0; i < myFields.Length; i++)
        {
            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);
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Reflection »




Array
Constructor
Event
Field
Interface
Method
Properties
Type