C# - Print Constructors of a Class Using ConstructorInfo

Learn, how to print constructors of the specified class using ConstructorInfo class in C#?
Submitted by Nidhi, on October 28, 2020 [Last updated : March 22, 2023]

Here, we will print constructors of the specified class using the predefined reflection class ConstructorInfo, here we need to import the System.Reflection namespace in the program.

C# program to print constructors of the specified class using ConstructorInfo class

The source code to print constructors of the specified class using ConstructorInfo class is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to print constructors of the 
//specified class using ConstructorInfo class

using System;
using System.Reflection;

class Sample
{
    public Sample()
    {
        Console.WriteLine("Constructor1 called"); 
    }
    public Sample(int val)
    {
        Console.WriteLine("Constructor2 called with value: "+val);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Type type = typeof(Sample);

        Console.WriteLine("Constructors of Sample class:");
        ConstructorInfo[] ctors = type.GetConstructors();
        foreach (ConstructorInfo ctor in ctors)
        {
            Console.WriteLine("\t"+ctor);
        }  
    }
}

Output

Constructors of Sample class:
        Void .ctor()
        Void .ctor(Int32)
Press any key to continue . . .

Explanation

In the above program, we created two classes Sample and Program. Here, we imported the System.Reflection to use Assembly class.

The Program class contains the static method Main(), the Main() method is the entry point for the program.

Here, we created reference type of Type class which is initialized with type returned by typeof() operator, here we passed class Sample in the typeof() operator, and then we got the constructors using GetConstructors() method and then accessed the constructors using foreach loop one by one and printed on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





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