Sunday, 17 December 2017


Get method type and method name

Console.WriteLine("Enter TypeName:");
string TypeName = Console.ReadLine();

Type type = Type.GetType(TypeName);

MethodInfo[] methods = type.GetMethods();
foreach (MethodInfo method in methods)
{
    Console.WriteLine(method.ReturnType.Name + " " + method.Name);
}


Console application shows Return type and name of method; method display more than one time its overloaded methods. Full list
Get property and constructor
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo prop in properties)
{
    Console.WriteLine(prop.PropertyType.Name + " " + prop.Name);
}


ConstructorInfo[] constructor = type.GetConstructors();
foreach (ConstructorInfo cons in constructor)
{
    Console.WriteLine(cons.ToString());
}



Complete code:
using System;
using System.Reflection;

namespace Reflection
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter TypeName:");
            string TypeName = Console.ReadLine();

            Type type = Type.GetType(TypeName);

            MethodInfo[] methods = type.GetMethods();
            foreach (MethodInfo method in methods)
            {
                Console.WriteLine(method.ReturnType.Name + " " + method.Name);
            }

            PropertyInfo[] properties = type.GetProperties();
            foreach (PropertyInfo prop in properties)
            {
                Console.WriteLine(prop.PropertyType.Name + " " + prop.Name);
            }

            ConstructorInfo[] constructor = type.GetConstructors();
            foreach (ConstructorInfo cons in constructor)
            {
                Console.WriteLine(cons.ToString());
            }

            Console.ReadKey();
        }
    }
}


No comments:

Post a Comment

Generic in c#

Generic used to code reuse, type safety and increase performance, it consists in declaring a Type with Type parameter that will be instant...