Indicates whether the field is public.
[Visual Basic] Public ReadOnly Property IsPublic As Boolean [C#] public bool IsPublic {get;} [C++] public: __property bool get_IsPublic(); [JScript] public function get IsPublic() : Boolean;
Read-only. true if this field is public; otherwise, false.
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 property is other than public, it is protected and cannot be readily accessed. To access a non public property, in the GetField method, set the BindingFlags to NonPublic.
[C#]
//Make two fields public class Myfielda // private { private string field = "private field"; public string Field{ get{return field;} } } public class Myfieldb // public { public string field = "public 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.NonPublic); Type MyTypeb = Type.GetType("Myfieldb"); FieldInfo Myfieldinfob = MyTypeb.GetField("field"); //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.field- private field; IsPublic = False; IsPrivate = True;
Myfieldb.field- public field; IsPublic = True; IsPrivate = False;
FieldInfo Class | FieldInfo Members | System.Reflection Namespace | FieldAttributes