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

Here, we are going to learn how to print constructors of the specified class using ConstructorInfo class in C#?
Submitted by Nidhi, on October 28, 2020

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.


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)


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


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 »


What's New (MCQs)

Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.