Reflection Odds and Ends

Some commonly used uses for reflection…

Assemblies

First, you need to get a reference to an assembly.

Either by name:

AssemblyName assemblyRef=new AssemblyName("MyAssembly");

or by loading from a file:

AssemblyName assemblyRef=Assembly.LoadFrom("c:\stuff\myassembly.dll");

If your code is running in an assembly that is being called by another assembly, and you need the path to the parent assembly, you can do this:

string assemblyPath=new Uri(Assembly.GetEntryAssembly().GetName().CodeBase).LocalPath;
Assembly assemblyDll=Assembly.LoadFrom(assemblyPath);

Types

An assembly has types, and a list of those types can be retrieved by using the GetTypes() method

Type[] allTypes=assemblyRef.GetTypes();

Some of those types are not public and are used for internal purposes. You probably want to ignore those. The IsPublic property of a type will let you know if the type is public.

foreach(Type oneType in allTypes)
   if (oneType.IsPublic)
      Console.WriteLine(oneType.Name);

To get a type for inspection using the string equivalent of the type name, use the GetType() function:

(MyType)thisType=myAssembly.GetType("MyType",true);

Retrieving the namespace of a type

To retrieve the namespace of a type use the NameSpace property:

MyType.Namespace;

Creating an instance of a type

To create an instance of a type, use the Activator.CreateInstance method

(MyType)Activator.CreateInstance(thisType);

or

(MyType)Activator.CreateInstance("MyNamespaceName.MyTypeName");

To create an instance of a type using specific parameters in a constructor:

(MyType)Activator.CreateInstance(thisType,parameters); //parameters is an array of type object.

Here is another example:

(MyType)Activator.CreateInstance(thisType,
                                 new Object[]
                                 {
                                     parm1,
                                     parm2,
                                     parm3
                                 });

 

Constructors

A type can have constructors. Each constructor is an object of type of ConstructorInfo, and each ConstructorInfo object has a collection of ParameterInfo objects that describe each parameter of the constructor.

ConstructorInfo[] ctors=type.GetConstructors();
   foreach(ConstructorInfo ctor in ctors)
      foreach(ParameterInfo parmInfo in ctor.GetParameter())
         Console.WriteLine(parmInfo.ParameterType.ToString())

Fields

A type has fields, which are the properties and constants associated with the type.

To retrieve a list of fields associated with a type, use the GetFields() function

FieldInfo[] fields=oneType.GetFields(
                            BindingFlags.Public
                            | BindingFlags.Static
                            | BindingFlags.FlattenHierachy);

Getting the value of a field

To get the value of a field, use the GetValue() function

object retVal=fields[0].GetValue(null);

Setting the value of a field

To set the value of a field, use the SetValue() function

myField.SetValue(myObjectInstance,myValue,null); //the NULL refers to the index of indexed properties.

Data type of fields

The TypeCode property of a field indicates what type it is, and can be retrieved using the GetTypeCode() function.

TypeCode thisFieldType=Type.GetTypeCode(myField)

TypeCode is an enumeration. Some of the TypeCode enumerations are:

  • TypeCode.Byte
  • TypeCode.Decimal
  • TypeCode.Double
  • TypeCode.Int16
  • TypeCode.Int32
  • TypeCode.Int64
  • TypeCode.SByte
  • TypeCode.Single
  • TypeCode.UInt16
  • TypeCode.UInt32
  • TypeCode.UInt64
  • TypeCode.Object

Attributes associated with fields

To retrieve field attributes use the GetCustomAttributes() function.

foreach(System.Attribute thisAttribute in thisType.GetCustomAttributes(true))
   Console.WriteLine(thisAttribute.GetType().ToString());

To define a custom attribute, create a class that inherits from System.Attribute

[AttributeUsage(AttributeTargets.All)]
public class MyCustomType : System.Attribute
{
    public MyCustomType()
    {
    }
}

Usage would then be as follows:

public class MyClass
{
    [MyCustomType]
    public string MyProperty{get;set;}
}