Getting the type of an object in .NET C#

You’ll probably know that every object in C# ultimately derives from the Object base class. The Object class has a GetType() method which returns the Type of an object.

Say you have the following class hierarchy:

public class Vehicle
{
}

public class Car : Vehicle
{
}

public class Truck : Vehicle
{
}

Read more of this post

Examining the Assembly using Reflection in .NET

The CLR code of a project is packaged into an assembly. We can inspect a range of metadata from an assembly that also the CLR uses to load and execute runnable code: classes, methods, interfaces, enumerations etc.

In order to inspect an Assembly in a .NET project we’ll first need to get a reference to the assembly in question. There are various ways to retrieve an assembly, including:

Assembly callingAssembly = Assembly.GetCallingAssembly();
Assembly entryAssembly = Assembly.GetEntryAssembly();
Assembly executingAssembly = Assembly.GetExecutingAssembly();

…where Assembly is located in the System.Reflection namespace.

Read more of this post

A basic example of using the ExpandoObject for dynamic types in .NET C#

The ExpandoObject in the System.Dynamic namespace is an interesting option if you ever need to write dynamic objects in C#. Dynamic objects are ones that are not statically typed and whose properties and methods can be defined during runtime. I’ve come across this object while I was discovering the dynamic language runtime (DLR) features in .NET. We’ve seen an example of that in this post with the “dynamic” keyword.

Read more of this post

An example of using the dynamic keyword in C# .NET

The dynamic keyword in C# is similar to Reflection. It helps you deal with cases where you’re not sure of the concrete type of an object. However, you may expect the object to have a certain method that you can invoke at runtime. E.g. you have a framework that external users can write plugins for. You may set up a list of rules for the plugin to be valid, e.g. it must have a method called “Execute” and a property called “Visible”.

There are various ways you can solve this problem and one of them is dynamic objects. Using the dynamic keyword will turn off the automatic type checking when C# code is compiled. The validity of the code will only be checked at runtime.

Read more of this post

A basic example of using the ExpandoObject for dynamic types in .NET C#

The ExpandoObject in the System.Dynamic namespace is an interesting option if you ever need to write dynamic objects in C#. Dynamic objects are ones that are not statically typed and whose properties and methods can be defined during runtime. I’ve come across this object while I was discovering the dynamic language runtime (DLR) features in .NET. We’ve seen an example of that in this post with the “dynamic” keyword.

Read more of this post

An example of using the dynamic keyword in C# .NET

The dynamic keyword in C# is similar to Reflection. It helps you deal with cases where you’re not sure of the concrete type of an object. However, you may expect the object to have a certain method that you can invoke at runtime. E.g. you have a framework that external users can write plugins for. You may set up a list of rules for the plugin to be valid, e.g. it must have a method called “Execute” and a property called “Visible”.

There are various ways you can solve this problem and one of them is dynamic objects. Using the dynamic keyword will turn off the automatic type checking when C# code is compiled. The validity of the code will only be checked at runtime.

Read more of this post

Create code at runtime with Reflection in .NET C#: Properties

In the previous post of this short series we saw how to add a field to our custom type using Reflection. In this finishing post we’ll look at properties and how to save our dynamic assembly.

Properties can be created in two ways. First we can use the PropertyBuilder class:

PropertyBuilder priceProperty = simpleType.DefineProperty("Price", PropertyAttributes.None, typeof(int), Type.EmptyTypes);

This will create a standard property called Price which returns an integer and has no input parameters. You’d write it like this in Visual Studio:

public int Price { get; set; }

For some reason the PropertyAttributes enumeration doesn’t let you refine the characteristics of the property as much as e.g. MethodAttributes or FieldAttributes do. In case you’d like to define the visibility of the property you need to turn to the MethodBuilder object and use it in a special way. The methods will perform the get/set methods separately. The following code example creates a get and set method:

MethodAttributes pricePropertyAttributes = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
MethodBuilder getPriceBuilder = simpleType.DefineMethod("get_Price", pricePropertyAttributes, typeof(int), Type.EmptyTypes);
MethodBuilder setPriceBuilder = simpleType.DefineMethod("set_Price", pricePropertyAttributes, null, new Type[] { typeof(int) });
priceProperty.SetGetMethod(getPriceBuilder);
priceProperty.SetSetMethod(setPriceBuilder);

The SpecialName and HideBySig values indicate that these methods are special and will not be part of the public interface. The name of the get/set methods must follow a convention: “get_XXX” and “set_XXX” where ‘XXX’ is the name of the property like get_Price.

The special methods can be associated with the property using the SetGetMethod and SetSetMethod methods of the PropertyBuilder object.

Once you’re done with your custom assembly then it can be persisted on disk using the Save method of AssemblyBuilder:

assemblyBuilder.Save(assemblyFileName);

View all posts on Reflection here.

Create code at runtime with Reflection in .NET C#: Fields

In the previous post of this short series we saw how to create a method using Reflection.

We can also create fields in our custom type. Here’s how to create a standard private field:

FieldBuilder fieldBuilder = simpleType.DefineField("_price", typeof(int), FieldAttributes.Private);

You can use the FieldAttributes enumeration to modify the properties of the field. E.g. here’s how to declare the field public and readonly – which is not a very clever combination, but there you have it:

FieldBuilder fieldBuilder = simpleType.DefineField("_price", typeof(int), FieldAttributes.InitOnly | FieldAttributes.Public);

View all posts on Reflection here.

Create code at runtime with Reflection in .NET C#: Methods

The previous post in this miniseries got us as far as defining a default and an overloaded constructor for our custom type:

ConstructorBuilder defaultConstructorBuilder = simpleType.DefineDefaultConstructor(MethodAttributes.Public);
ConstructorBuilder constructorBuilder = simpleType.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(string) });

We can add methods to the type in the following ways. Here’s how to create a void method called Calculate which accepts two integers as parameters:

MethodBuilder calculateFunctionBuilder = simpleType.DefineMethod("Calculate", MethodAttributes.Public, null, new Type[] { typeof(int), typeof(int) });

Note the ‘null’ parameter which defines that there’s no return type. Consequently here’s how to add a return type of int:

MethodBuilder calculateFunctionBuilder = simpleType.DefineMethod("Calculate", MethodAttributes.Public, typeof(int), new Type[] { typeof(int), typeof(int) });

If there are no parameters to the method then leave the last item as null:

MethodBuilder calculateFunctionBuilder = simpleType.DefineMethod("Calculate", MethodAttributes.Public, typeof(int), null);

…and here’s how to define a static method:

MethodBuilder calculateFunctionBuilder = simpleType.DefineMethod("Calculate", MethodAttributes.Public | MethodAttributes.Static, typeof(int), null);

We’ll of course need a method body as well and just like we saw in the case of constructors this operation can be quite complex. Check the post on creating constructors programmatically for my notes and links regarding the .NET intermediate language instructions, the ILGenerator and OpCodes objects for further information.

View all posts on Reflection here.

Create code at runtime with Reflection in .NET C#: Constructor

The previous post in this miniseries got us as far as defining a type using the TypeBuilder object:

TypeBuilder simpleType = moduleBuilder.DefineType("PluginSimpleType", TypeAttributes.Class | TypeAttributes.Public);
TypeBuilder extendedType = moduleBuilder.DefineType("PluginExtendedType", TypeAttributes.Class | TypeAttributes.Public, typeof(Customer), new Type[] {typeof(IEqualityComparer), typeof(IEquatable<int>) });

The TypeBuilder object is the entry point to creating the members of the Type such as constructors and methods. Here’s how you can create a public constructor with a string parameter:

ConstructorBuilder constructorBuilder = simpleType.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(string) });

If there’s no constructor for the Type then a default parameterless constructor is automatically created for you. If you declare an overloaded constructor like above then there will be no default constructor – this should be familiar to you from everyday OOP in .NET and Java. If you’d like to have a default empty constructor like this…

public Customer()
{
}

…besides the overloaded constructor then you can call the DefineDefaultConstructor method:

ConstructorBuilder defaultConstructorBuilder = simpleType.DefineDefaultConstructor(MethodAttributes.Public);

Otherwise if you’d like to have a parameterless constructor which has a body, i.e. does more than call the default constructor of the base class then you need to use the DefineConstructor method again:

ConstructorBuilder constructorBuilder = simpleType.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);

Note the ‘null’ to denote 0 parameters.

This is not the end of the story. We need to attach a method body to the constructors(s) defined by the DefineConstructor method. We can leave the parameterless default constructor as it is, we don’t need any method body implementation for it.

This is where creating assemblies in code can become quite challenging.

Creating your method body requires intimate knowledge of the Microsoft Intermediate Language instructions that all .NET languages are translated into when compiled. I won’t even pretend that I know much about these instructions. The ILGenerator object can somewhat help you out so that you don’t need to write the actual byte code.

The OpCodes class stores more than 1000 instructions such as Ret for return, Call to call another method or Neg for negating a value.

You can get the ILGenerator object from the builder and call its Emit method to emit IL instructions. This is how you’d add a return statement:

ILGenerator msilGenerator = constructorBuilder.GetILGenerator();
msilGenerator.Emit(OpCodes.Ret);

More information about dynamic methods is available on MSDN here and here.

View all posts on Reflection here.

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

ARCHIVED: Bite-size insight on Cyber Security for the not too technical.