Instantiating Generic Types

by Administrator 8. September 2011 02:49

On an MVC project I came to a point where I wanted to pass a generic ViewModel<Person> type to a view. However the source of the data provides ViewModel<IDomainObject>, where IDomainObject is an interface Person implements. If you want to defer the type when creating object instances, you can make use of the Activator class:

Activator.CreateInstance (typeof(StringBuilder));

This is equivalent to

new StringBuilder()

However the benefit is that you do not need to know the type you create at compile time anymore. Of course the drawback is that you lose type checking.

The activator also supports passing in parameters:

Activator.CreateInstance (typeof(StringBuilder), "Hi Mom");

This is equivalent to

new StringBuilder("Hi Mom")

Now for my problem it becomes a little more tricky since I want to new up a generic type. I found this post that pointed me to the right direction, however I found constructing the string from the base type with an added number for the number of generic arguments a little odd and poked at MSDN. Probably more elegant is this:

Activator.CreateInstance( typeof( ViewModel<> ).MakeGenericType( targetType )

The interesting thing here is, that you can create a type of the generic without setting the type parameters. Then you can use the MakeGenericType method to put the parameters in place. In this approach you can as well pass in any constructor parameters you like.

Tags: , ,

C#

Useful Extension methods

by Administrator 3. September 2011 02:46

Most of the time you will be just cosuming extension methods, however there are a few really useful ones, e.g. ForEach (which allows executing a statement on each item in an enumerable).

You'll often see constructs like the one below to perform parameter validation:

if (parameter == null)
{
   throw new ArgumentException ("parameter");
}

if (string.IsNullOrEmpty (parameter2))
{
   throw new ArgumentException ("parameter2");
}

One way to keep this code less verbose ist to use code contracts. These were added to the core framework with v4.0 and originally came out of Microsoft Research. With code contracts you would do it like this:

Contract.Requires(parameter != null);
Contract.Requires(!string.IsNullOrEmpty (parameter2));

Code Contracts allow to do much more, the idea is to make assumptions more explicit. I did not dive too deep into the topic, but as far as I know, there is more going on behind the covers than just checking the expressions, you can add input and output conditions to methods and get much better errors when these break.

If you do not want to go this route, check out these two extension methods:

public static class ExtensionHelpers
{
    public static void Require<T>(this object requiredParameter, Expression<Func<T>> accessor)
    {
        if (requiredParameter == null)
        {
            throw new ArgumentNullException(((MemberExpression)accessor.Body).Member.Name);
        }

    }

    public static void Require(this string requiredParameter, Expression<Func<string>> accessor)
    {
        if (string.IsNullOrEmpty (requiredParameter))
        {
            throw new ArgumentNullException(((MemberExpression)accessor.Body).Member.Name);
        }
    }
}

With these methods in place, the validation from above would look like this:

param.Require(() => param);
param2.Require(() => param2);

The lamda expression is in place to allow to extract the name of the parameter. Otherwise you would have to specify the name as a string for the exception to throw. The good news about this syntax is, that it even survives renaming parameters.

Tags: , ,

My Stuff | C#

About the author

for comments and suggestions contact:

 

Month List