Skip Navigation LinksHome > View Post

Using Generics as Parameters

Anybody who uses Spring .NET or software factories in general has probably written a method something like this:

public class Factory
{
    public object CreateInstance(Type type)
    {
        // using Spring.NET factory
        return ContextRegistry.GetContext().GetObject(type.FullName);
    }
}

which is used like this:

ISomeObject someObject = (ISomeObject) _factory.CreateInstance(typeof(ISomeObject));

However, why not try a generic method:

public class Factory
{
    public T CreateInstance<T>()
    {
        // using Spring.NET factory
        return (T) ContextRegistry.GetContext().GetObject(typeof(T).Fullname);
    }
}

which would be used like this:

ISomeObject someObject = _factory.CreateInstance<ISomeObject>();

Which I think is much nicer :)

UPDATE: Dusty posted another great example on his blog (if you overlook the catching all exceptions for which I assume Dusty has his reasons). Check it out (+ thanks for your kind words Dusty).

Tags: .NET

 
Josh Post By Josh Twist
2:01 AM
03 May 2006

» Next Post: Softer Tips for Smoke Tests
« Previous Post: New features in IIS7

Comments are closed for this post.

Posted by Dusty @ 03 May 2006 10:46 AM
The generic version is much nicer indeed. In fact, I was trying something like this just about a week ago, and gave up, settling with passing the Type. Just re-implemented it with the generic methods and it works great. Thanks for the example!

Posted by Nick Parker @ 07 May 2006 6:32 PM
Josh,
I had written something similar to this for Spring.NET and generics last year, however mine also included attaching advisors to intercept method calls. If your interested, take a look:

http://developernotes.com/archive/2005/10/19/757.aspx

Nick Parker

Posted by Seth Flowers @ 16 Feb 2007 1:21 PM
I am unfamiliar with Spring.Net, so you may have to disregard my post. However, isn't it the case that if ContextRegistry.GetContext().GetObject(..) returns anything other than T, you are still performing a cast to T ( I don't know how the CLR handles casts between equal types ). If this is true, then the sample generic code will perform no better than the non-generic code. The only benefit is the improved elegance from the lack of casting required from the calling code. In effect the cast was just moved down a method.

Posted by Josh @ 17 Feb 2007 12:29 PM
Who said anything about improved performance? :)

© 2005 - 2014 Josh Twist - All Rights Reserved.