Features Of System Reflection


Hello everybody,

today I want to document few features of System.Reflection namespace.

It has following important types:

Type ( with methods GetType, GetMemberInfo, GetPropertyInfo, GetFieldInfo ), Activator ( with method CreateInstance ), Assembly ( Load, LoadFrom, GetTypes, GetName, GetFiles ), ILGenerator ( Emit ).

Some code fragments for reflection

var lst = new List<double>();

Type listType = typeof(List<double>);

Type[] pars = {typeof(double)};

MethodInfo addMeth = listType.GetMethod("Add", pars);

addMethod.Invoke(lst, new object[] {8.3});

Create an isntace of type:

public static Type GetType(string typeName)

public static object CreateInstance(Type type)

How to work with interfaces

public static Assembly LoadFrom(string assemblyFile); // load assembly

public IEnumberable<Type> ExportedTypes {get; }// Get types exposed on an Assembly

public bool IsAssinableFrom( Type c ); //check if type implements interface

public bool IsSubClassOf(Type c); // check if type inherits another type

public bool IsClass {get; } // check if type is a class

Fully-Qualified type name

Suppose you want to create some instance of interface implementation. You can see following Fully-qualified name:

Repository.Interface.IRepository`2[SomeClass1, System.String]

Question: for what stands 2 after back tick symbol? 2 says the following: Repository.Interface.IRepository has 2 generic type parameters.

Sample of search and Load

IEnumerable<string> assemblyFiles = Directory.EnumerateFiles(assemblyPath, "*.dll", SearchOption.TopDirectoryOnly);

foreach (string assemblyFile in assemblyFiles)
      Assembly assembly = Assembly.LoadFrom(assemblyFile);
      foreach (Type type in assembly.ExportedTypes)
            if (type.IsClass && typeof(ISomeInterface).IsAssignableFrom(type))
                        ISomeInterface interfaceInstance = Activator.CreateInstance(type) as ISomeInterface;
                        implementations.Add(new DynamicOrderRule(interfaceInstance, type.FullName, type.Assembly.GetName().Name));



No Comments


Add a Comment


Comments are closed