Skip to main content

Reflection

Is the ability to inspect and change information about assemblies, types and code at runtime. Is used for plugin development, logging, code analysis etc. Assemblies contain modules => Modules contain types => Types contain code

var a = Assembly.LoadFrom("MyAssembly.dll");
var b = Assembly.GetExecutingAssembly();

// List all types in assembly
Type[] types = a.GetTypes();
foreach (var t in types)
Console.WriteLine(t.FullName);
Type t = assembly.GetType("Namespace.SomeClass");
foreach (MethodInfo m in t.GetMethods())
Console.WriteLine(m.Name);

object o = a.CreateInstance("MyPlugin.HelloWorld");
Type hwClass = a.GetType("MyPlugin.MethodInfo");
MethodInfo mi = hwClass.GetMethod("ToString"); // by default only public
MethodInfo mi = hwClass.GetMethod("SayItPrivate", BindingFlags.Instance |
BindingFlags.NonPublic);
object retVal = mi.Invoke(o, null);
// Does class implement interface?
Type type = assembly.GetTypes () // scan all types
.Where(t => t.IsClass) // it must by a class , that
.Single(t => t.GetInterface("IMyInterface" != null ); // implements my interface
IMyInterface myObj = assembly.CreateInstance(type.FullName) as IMyInterface;
// call method
double res = myObj.DoSomething("input", 20);

csharpReflectionApi

System.Type

Represents type declarations: class types, interface types, array and value types, enumeration types, type parameters, and more. Value, Interface or Class? => IsValueType , IsInterface , IsClass Public, Private or Sealed => IsNotPublic , IsSealed Abstract or Implementation? => IsAbstract

Attributes

[Serializable]
class C {...} // marks the class as serializable

// will force compiler to produce a message
public class ObsoleteAttribute : Attribute
{
public string Message { get {...}
public bool IsError { get {...} set {...}
public ObsoleteAttribute() {...}
public ObsoleteAttribute(string msg) {...}
public ObsoleteAttribute(string msg , bool error) {...}
}

[Obsolete("Message Use class C1 instead", true)]
public class C {.. }

// Querying attributes at runtime
Type t = typeof(C);
object[] a = t.GetCustomAttributes(typeof(Comment), true);
Comment ca = (Comment)a[0];
Console.WriteLine(ca.Text + ", " + ca.Author);

AttributeUsage

public class AttributeUsageAttribute : Attribute{
public AttributeUsageAttribute(AttributeTargets validOn){...}
public bool AllowMultiple { get; set; } // default: false
public bool Inherited { get; set; } // default: true
public AttributeTargets ValidOn { get; set; } // default: All
public virtual Object TypeId {get;}
}

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
public class MyAttribute : Attribute {...}

validOn => to which program elements is the attribute applicable? AllowMultiple => can it be applied to the same program element multiple times? Inherited => is it inherited by subclasses? TypeID => when implemented, gets unique identifier for derived attribute classes