C# - Check a Specified Type is Public or Not?

Learn, how to check a specified type is public or not in C#?
Submitted by Nidhi, on October 30, 2020 [Last updated : March 22, 2023]

Checking a type is a public or not

Here, we will check a specified type is a public or not using IsPublic property of Type class.

C# program to check a specified type is public or not

The source code to check a specified type is public or not is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# - Check a Specified Type is Public or Not?.

using System;
using System.Reflection;

class Sample
{ 
    public static void Print()
    {
        Console.WriteLine("Print() method called");
    }
}

class Program
{
    static void Main()
    {
        Type type = typeof(Sample);

        if (type.IsPublic == true)
        {
            Console.WriteLine("Sample is a public class");
        }
        else
        {
            Console.WriteLine("Sample is not a public class");
        }
    }
}

Output

Sample is not a public class
Press any key to continue . . .

Explanation

In the above program, we created two classes Sample and Program. The Sample class contains a static Method Print(), and the Program class contains the Main() method. The Main() method is the entry point for the program. Here we check the specified type is public or not using the IsPublic property of Type class and printed the appropriate message on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.