C# Reflection

C# Code Snippets Reflection
Share:

About

In this code snippet, we will take a look at reflection in C#.

Reflection is used to get metadata(information) about an object at runtime. We can get members(propertiesmethods) of objects and their data types. Reflection is also used for late binding. The ability to see the metadata of an object is for example, useful is when you use generics, as you don’t necessarily know the data type of a generic member until the object is created.

Let’s look at the code example below to see how reflection is used.

Code:

using System;
//Add this.
using System.Reflection;

namespace Reflection
{
    class Program
    {
        static void Main(string[] args)
        {
            //Specify namespace.class and get back a Type object that contains all the info about namespace.class.
            Type T = Type.GetType("Reflection.MyClass");

            //Or ...

            Type T2 = typeof(MyClass);

            //Get methods, classes, properties, ... and save them in an array. 
            PropertyInfo[] properties =  T.GetProperties();
            MethodInfo[] methods = T.GetMethods();

            //Iterate through array and write out the attributes of your methods, classes, properties, ....
            foreach (var property in properties)
            {
                Console.WriteLine("Full property: "+property+", Name: "+property.Name + ", Type: " + property.PropertyType.Name);
            }

            foreach (var method in methods)
            {
                Console.WriteLine("Full Method: " + method + ", Name: " + method.Name + ", Type: " + method.ReturnType.Name);
            }

            Console.ReadLine();
        }
    }

    class MyClass
    {
        public int MyFirstProperty { get; set; }
        public int MySecondProperty { get; set; }
        public string MyThirdProperty { get; set; }

        public void MyMethod()
        {
            Console.WriteLine("MyMethod did this.");

        }

        public void MySecondMethod()
        {
            Console.WriteLine("MySecondMethod did this.");
        }

    }
}

Resulting output:

Share:

Leave a Reply

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

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger