Posts tagged ‘reflection’

Simple but Elegant, Creating a class from String

Creating a class from a string might be crucial for some very dynamic projects. It’s a single line of code that I wanted to share but I think it has a lot of power.

Simply get the executing assembly and call the GetType method. If your assembly is one of the linked assembly or even a dynamically loaded assembly, you might need to call GetReferencedAssemblies() method as well.

namespace reflectme
{
    using System;
    public class hello
    {
        public hello()
        {
            Console.WriteLine("hello");
            Console.ReadLine();
        }
        static void Main(string[] args)
        {
            Type t = System.Reflection.Assembly.GetExecutingAssembly().GetType("reflectme.hello");
            t.GetConstructor(System.Type.EmptyTypes).Invoke(null);
        }
    }
}

Bear in mind it will be extremely slow. Don’t do that :)

Reflection with Private Members

By using reflection we can call any function including the private and protected ones. This includes private static methods, constructor methods, normal methods. What we need to do is to get the method by the BindingFlags.Nonpublic flag and then we just use it like a reflected type.

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
 
namespace ReflectPrivateMembers
{
    class Program
    {
        static void Main(string[] args)
        {
            ConstructorInfo ci = typeof(Hello).GetConstructor(BindingFlags.NonPublic| BindingFlags.Instance ,null,System.Type.EmptyTypes,null);
            object helloObject = ci.Invoke(System.Type.EmptyTypes);
            MethodInfo[] helloObjectMethods = helloObject.GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly| BindingFlags.Instance );
 
            foreach (MethodInfo mi in helloObjectMethods)
            {
                mi.Invoke(helloObject, System.Type.EmptyTypes);
            }
            Console.ReadLine();
        }
    }
    public class Hello
    {
        private Hello()
        {
            Console.WriteLine("Private Constructor");
        }
        public void HelloPub()
        {
            Console.WriteLine("Public Hello");
        }
        private void HelloPriv()
        {
            Console.WriteLine("Private Hello");
        }
    }
}