Thursday, January 22, 2015

Overview

Reflection is the ability to make modifications at runtime by making use of introspection. Type Introspection is the ability to inspect the code in the system and see object types. C#’s reflectin is beautiful. See the example below. More info can be found here.

Example

Given

1
2
3
4
5
6
7
8
9
10
11
12
public class BaseClass {
    // ...
}
public class Jake : BaseClass, ITest {
    // ...
}
public class Tom : ITest {
    // ...
}
public class Random : BaseClass {
    // ...
}

You can do the following

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Instantiator {
    public static void InstantiateITest() {
        var instances = from t in Assembly.GetExecutingAssembly().GetTypes()  // Get every class
                        where t.GetInterfaces().Contains(typeof(ITest))       // That implements ITest interface
                              && t.GetConstructor(Type.EmptyTypes) != null    // and has a constructor
                        select Activator.CreateInstance(t) as ITest;          // create an instance
        foreach(var instance in instances) {
            // do something with them
        }
        // instances = [Jake, Tom]
    }

    public static void InstantiateBaseClasses() {
        var instances = from t in Assembly.GetExecutingAssembly().GetTypes()  // Get every class
                        where t.IsSubClassOf(typeof(BaseClass))               // That derives from BaseClass
                              && t.GetConstructor(Type.EmptyTypes) != null    // and has a constructor
                        select Activator.CreateInstance(t) as BaseClass       // create an instance
        foreach(var instance in instances) {
            // do something with them
        }
        // instances = [Jake, Random]
    }
}

Random Posts