Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

C# Program to Check a Specified Type is Public or not

  • Last Updated : 23 Nov, 2021

A class is a collection of methods, variables, and objects. We can create a public class, private class, or protected class using the access modifiers. A class created with the public modifier will have access entirely to a program. So to check whether the given class or type is a public type or not we use the IsPublic property of the Type class. It will return true if the given type is a public type. Otherwise, it will return false. Also, this property will not work with nested types.

Syntax:

public bool IsPublic { get; }

Example 1:

C#




// C# program to check whether the given class or
// type is a public type or not
using System;
using System.Reflection;
  
// Declare a class with public modifier
public class Myclass1
{
    public void display()
    {
        Console.WriteLine("Hello! GeeksforGeeks");
    }
}
  
// Declare a class without public modifier
class Myclass2
{
    public void Show()
    {
        Console.WriteLine("Hey! GeeksforGeeks");
    }
}
  
public class GFG{
  
// Driver code    
public static void Main(string[] args)
{
      
    // Check the given type is a public or not
    // Using IsPublic property
    Console.WriteLine(typeof(Myclass1).IsPublic);
    Console.WriteLine(typeof(Myclass2).IsPublic);
}
}

Output:

True
False

Example 2:

C#




// C# program to check whether the given class or
// type is a public type or not
using System;
using System.Reflection;
  
// Declare a class with public modifier
public class Student
{
    public void display()
    {
        Console.WriteLine("I like C# languagea alot");
    }
}
  
public class GFG{
  
// Driver code    
public static void Main(string[] args)
{
      
    // Check the given type is a public or not
    // Using IsPublic property
    if (typeof(Student).IsPublic == true)
    {
        Console.WriteLine("The given class is a public class");
    }
    else
    {
        Console.WriteLine("The given class is not a public class");
    }
}
}

Output:

The given class is a public class


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!