Check if a field is public in CSharp

Description

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

Example


using System;/*from w w  w. ja  va  2  s  . c  om*/
using System.Reflection;

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 class Myfieldinfo{
    public static int Main()
    {
        Myfielda Myfielda = new Myfielda();
        Myfieldb Myfieldb = new Myfieldb();

        Type MyTypea = typeof(Myfielda);
        FieldInfo Myfieldinfoa = MyTypea.GetField("SomeField", BindingFlags.NonPublic|BindingFlags.Instance);
        Type MyTypeb = typeof(Myfieldb);
        FieldInfo Myfieldinfob = MyTypeb.GetField("SomeField");

        Console.Write("\n{0}.", MyTypea.FullName);
        Console.Write("\n   IsPublic = {0}", Myfieldinfoa.IsPublic);
        Console.Write("\n   IsPublic = {0}", Myfieldinfob.IsPublic);
        return 0;
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Reflection »




Array
Constructor
Event
Field
Interface
Method
Properties
Type