Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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)
        {
            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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | Class, Object, Methods

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to print properties of the specified cl... >>
<< C# program to print method names and its parameter...