C#

C# Reflection – Type class

A Type class is an important class in C# reflection. Type class represents class types, interface types, array types, value types, enum types, type parameters, generic type definitions, and open/closed generic types.

Type class helps you to find properties, methods, events, fields, and constructors declared in a type. It also provides us the Assembly in which the type is declared.

There are two ways to get the instance of Type class.

  1. typeof(ClassName)
  2. obj.GetType() instance method

GetType() is an instance method that means you can only use this method you have an object of that particular Type.

Program p = new Program(); 
Type t = p.GetType();

Whereas you can use typeof by only providing the type name.

Type t = typeof(Program);

Type class provides properties and methods to get the information about types.

NameDescription
Assembly propertyGets the Assembly class in which the type is declared.
BaseType propertyGets the Type from which the current Type inherits.
IsEnum propertyRepresents whether current Type is enumeration or not.
IsInterface propertyRepresents whether current Type is interface or not.
IsNested propertyRepresents whether current Type is nested in another Type.
IsNotPublic propertyRepresents whether current Type access modifier is not public or public.
IsPublic propertyRepresents whether current Type access modifier is public or not.
IsSealed propertyRepresents whether current Type is a sealed type or not.
IsValueType propertyRepresents whether current Type is a value type or not.
Namespace propertyGets the namespace of the Type.
GetConstructors methodReturns an array represents all public constructors of the Type.
GetConstructor methodReturns a specific constructor of the Type.
GetEvents methodReturns an array represents all public events of the Type.
GetEvent methodReturns a specific event the Type.
GetFields methodReturns an array represents all public fields of the Type.
GetField methodReturns a specific field of the Type.
GetMembers methodReturns an array represents all public members of the Type whether it is field, property, event or methods.
GetMember methodReturns a specific member of the Type.
GetProperties methodReturns an array represents all public properties of the Type.
GetProperty methodReturns a specific property of the Type.
GetMethods methodReturns an array represents all public methods of the Type.
GetMethod methodReturns a specific method of the Type.

Reflection Type Example

public class Program
{
        public event EventHandler MyEvent;
        public int MyField;
        public string MyProperty { get; set; }

        static void Main(string[] args)
        {
            Type obj = typeof(Program);
            Console.WriteLine("Assembly: " + obj.Assembly.FullName); // get assembly and it's full name
            Console.WriteLine("Base Type: " + obj.BaseType.FullName); // get base type and it's full name
            Console.WriteLine("IsEnum: " + obj.IsEnum); // Is current type enum
            Console.WriteLine("IsInterface: " + obj.IsInterface); // Is current type interface
            Console.WriteLine("IsNested: " + obj.IsNested); // Is current type nested class
            Console.WriteLine("IsNotPublic: " + obj.IsNotPublic); // Is current type not public
            Console.WriteLine("IsPublic: " + obj.IsPublic); // Is current type public
            Console.WriteLine("IsSealed: " + obj.IsSealed); // Is current type sealed
            Console.WriteLine("IsValueType: " + obj.IsValueType); // Is current type value type
            Console.WriteLine("Namespace: " + obj.Namespace); // current type namespace
            Console.WriteLine("Constructors: " + obj.GetConstructors().Count()); // current type constructors
            Console.WriteLine("Default Constructor: " + obj.GetConstructor(new Type[] { }).Name); // current type constructors
            Console.WriteLine("Events: " + obj.GetEvents().Count()); // current type events
            Console.WriteLine("Specific Event: " + obj.GetEvent("MyEvent").Name); // current type specific event
            Console.WriteLine("Fields: " + obj.GetFields().Count()); // current type field
            Console.WriteLine("Specific Field: " + obj.GetField("MyField").Name); // current type specific field
            Console.WriteLine("Members: " + obj.GetMembers().Count()); // current type members
            Console.WriteLine("Specific Member: " + obj.GetMember("MyField")); // current type specific member
            Console.WriteLine("Properties: " + obj.GetProperties().Count()); // current type properties
            Console.WriteLine("Specific Property: " + obj.GetProperty("MyProperty").Name); // current type specific property
            Console.WriteLine("Methods: " + obj.GetMethods().Count()); // current type methods
            Console.WriteLine("Specific Method: " + obj.GetMethod("Method1").Name); // current type specific method

            Console.ReadLine();
        }

        public void Method1()
        {
        }
}

TypeInfo Class

In the .NET 4.5 framework a new class TypeInfo is introduced that inherit from the Type class. TypeInfo is just a wrapper around Type class.

TypeInfo introduced some new properties and methods that will help to work with reflection easily. TypeInfo properties returns IEnumerable interface so that you can use LINQ queries easily.

Below is the list of important properties and methods of TypeInfo class.

NameReturnsDescription
DeclaredConstructors propertyIEnumerable<ConstructorInfo>Gets a collection of constructors
DeclaredEvents propertyIEnumerable<EventInfo>Gets a collection of events
DeclaredFields propertyIEnumerable<FieldInfo>Gets a collection of fields
DeclaredMembers propertyIEnumerable<MemberInfo>Gets a collection of members
DeclaredMethods propertyIEnumerable<MethodInfo>Gets a collection of methods
DeclaredProperties propertyIEnumerable<PropertyInfo>Gets a collection of properties
DeclaredNestedTypesIEnumerable<TypeInfo>Gets a collection of nested types
ImplementedInterfaces propertyIEnumerable<Type>Gets a collection of interfaces implemented
AsType methodTypeReturns the current type as Type object
GetDeclaredEvent methodEventInfoReturns a specific public event
GetDeclaredField methodFieldInfoReturns a specific public field
GetDeclaredMethod methodMethodInfoReturns a specific public method
GetDeclaredMethods methodIEnumerable<MethodInfo>Returns a collection of methods that match the name specify in the parameter. For overloaded methods
GetDeclaredProperty methodPropertyInfoReturns a specific public property
IsAssignableFromboolReturn True if specific type in parameter can be assigned to current type.

Getting TypeInfo Instances

There are also two ways for getting the instance of TypeInfo.

  1. obj.GetType().GetTypeInfo()
  2. typeof(ClassName).GetTypeInfo()

TypeInfo Example

using System;
using System.Linq;
using System.Reflection;

namespace ReflectionTest
{
    public class Program
    {
        public event EventHandler MyEvent;
        public int MyField;
        public string MyProperty { get; set; }

        static void Main(string[] args)
        {
            TypeInfo typeInfo = typeof(Program).GetTypeInfo();

            print("Declared Constructors: " + typeInfo.DeclaredConstructors.First().Name);
            print("Declared Events: " + typeInfo.DeclaredEvents.Count());
            print("Declared Fields: " + typeInfo.DeclaredFields.Count());
            print("Declared Members: " + typeInfo.DeclaredMembers.Count());
            print("Declared Methods: " + typeInfo.DeclaredMethods.Count());
            print("Declared Properties: " + typeInfo.DeclaredProperties.Count());
            print("Declared Nested Types: " + typeInfo.DeclaredNestedTypes.Count());    //Returns 0
            print("Implemented Interfaces: " + typeInfo.ImplementedInterfaces.Count()); //Returns 0

            print("AsType: " + typeInfo.AsType().Name); //Returns "Program"

            print("GetDeclaredEvent: " + typeInfo.GetDeclaredEvent("MyEvent").Name);
            print("GetDeclaredField: " + typeInfo.GetDeclaredField("MyField").Name);
            print("GetDeclaredMethod: " + typeInfo.GetDeclaredMethod("Method1").Name);
            print("GetDeclaredProperty: " + typeInfo.GetDeclaredProperty("MyProperty").Name);

            print("GetDeclaredMethods: " + typeInfo.GetDeclaredMethods("OverloadedMethod").Count());    //Returns 2

            print("IsAssignableFrom: " + typeInfo.IsAssignableFrom(typeof(Program)));   //return true
            print("IsAssignableFrom: " + typeInfo.IsAssignableFrom(typeof(int)));   //return false
        }

        public void Method1()
        {
            if (MyEvent != null)
            {
                MyEvent(this, EventArgs.Empty);
            }
        }

        public void OverloadedMethod(int i)
        {
            if (MyEvent != null)
            {
                MyEvent(this, EventArgs.Empty);
            }
        }

        public void OverloadedMethod(string str)
        {
            if (MyEvent != null)
            {
                MyEvent(this, EventArgs.Empty);
            }
        }

        static void print(string par)
        {
            Console.WriteLine(par);
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.