C# - Print Class and Method Names Using Reflection

Learn, how to print class names and its method names using reflection classes in C#?
Submitted by Nidhi, on October 28, 2020 [Last updated : March 22, 2023]

Here, we will print class names and its method names using predefined reflection classes Assembly and MethodInfo.

C# program to print class names and its method names using reflection classes

The source code to print class names and its method names using reflection classes is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to print class names and its method 
//names using reflection classes

using System;
using System.Reflection;

class Sample
{
    int num1;
    int num2;

    public void SetValues(int n1, int n2)
    {
        num1 = n1;
        num2 = n2;
    }

    public void PrintValues()
    {
        Console.WriteLine("Num1 :"+ num1);
        Console.WriteLine("Num2 :"+ num2);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Assembly asm; 
        Type[] types; 

        asm     = Assembly.GetExecutingAssembly();
        types = asm.GetTypes();

        foreach (Type cls in types)
        {
            Console.WriteLine(cls.Name);
            
            MethodInfo[] methodNames = cls.GetMethods();
            foreach (MethodInfo method in methodNames)
            {
                Console.WriteLine("\t"+method.Name);
            }
        }
    }
}

Output

Sample
        SetValues
        PrintValues
        ToString
        Equals
        GetHashCode
        GetType
Program
        ToString
        Equals
        GetHashCode
        GetType
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 asm of assembly class which is initialized with object returned by the GetExecutingAssembly(), and then we get types from the current program assembly and printed the name of classes that are created within the current program. After that, we got the name of methods created within the classes using the GetMethods() method of MethodInfo class and printed them on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





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