Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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 whether 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# language alot");
    }
}
 
public class GFG{
 
// Driver code   
public static void Main(string[] args)
{
     
    // Check whether 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


Last Updated : 27 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads