[Solved] Check if a class is public or private


Since you already determined the type (typeof(Jedi)) you are almost there. The Type class has two properties: IsPublic and IsNonPublic. You can use them to determine the access mode of your types:

public class Public
{ }
internal class Program
{
    private class Private
    {

    }
    [STAThread]
    private static void Main(string[] args)
    {
        Private pr = new Private();
        Console.WriteLine(pr.GetType().IsPublic); // false
        Public pu = new Public();
        Console.WriteLine(pu.GetType().IsPublic); // true

    }

}

But there are some pitfalls. As already mentioned in the comments, you will hardly be able to create an instance of a private class, unless it was declared inside the same class as the method that is trying to determine the access modifier.

Furthermore, these properties (IsPublic) determines the effective access to the type. So if you declare a public class inside an internal class, IsPublic will return false again:

internal class Program
{
    public class Public
    { }

    [STAThread]
    private static void Main(string[] args)
    {
        Public pu = new Public();
        Console.WriteLine(pu.GetType().IsPublic); // false, because Program is internal
    }
}

Depending on what you are trying to achieve, there may be more interesting solutions using reflection. You may want to read again the MSDN articles on the Type class.

UPDATE

The TypeInfo class has more properties like IsNested, IsNestedPublic and IsNestedPrivate. You can access that via:

TypeInfo info = obi.GetType().GetTypeInfo();

I’m still not sure why you want to determine this, but maybe using these properties and the Type.DeclaringType property you can infer the information you need.

2

solved Check if a class is public or private