all groups > dotnet clr > march 2007 >
You're in the

dotnet clr

group:

Using Generics vs Passing System.Type as argument?



Using Generics vs Passing System.Type as argument? Kenneth Baltrinic
3/16/2007 3:08:57 PM
dotnet clr: I have am currently working on a set of c# utility methods that all require
a System.Type object as an input argument, either soley or along with other
arguments. In call cases the calling methods are not working with variables
of System.Type, they just know the type at compile time that they need to
pass in and pass it by invoking typeof on the type. It has occurred to me
that I could implement all these methods as generic and thus the calling
code would not have to be invoking typeof all the time, it could be invoked
within the utility methods just once per method. As in the examples below,
are there any disadvantages to example B or example A? I see an obvious
advantage of being able to do compile time type checking by using a where
statement assert constraints, but currently that is not needed.

Example A:

//Client code:
Utils.MethodA( typeof(ClassA), arg2, arg3);
Utils.MethodA( typeof(ClassB), arg2, arg3);

//Utility class
public static class Utils
{
public static void MethodA( Type type , object arg2, object arg3)
{
...
}
}

Example B:

//Client code:
Utils.MethodA<ClassA>( arg2, arg3);
Utils.MethodA<ClassB>( arg2, arg3);

//Utility class
public static class Utils
{
public static void MethodA<theType>( object arg2, object arg3)
{
Type type = typeof(theType);
...
}
}

Re: Using Generics vs Passing System.Type as argument? VJ
3/17/2007 9:45:02 AM
The key for you should be to avoid unnecessary boxing/un-boxing. So what
ever is going to minimize that you can use that method..

VJ

[quoted text, click to view]

Re: Using Generics vs Passing System.Type as argument? VJ
3/17/2007 4:07:44 PM
Very true Jon. Also the more hirearchy you introduce, the more tough it
becomes to maintain code. Which is also a problem.

VJ

[quoted text, click to view]

Re: Using Generics vs Passing System.Type as argument? Jon Skeet [C# MVP]
3/17/2007 7:22:32 PM
[quoted text, click to view]

That depends on the context. If it's not performance critical (as most
methods aren't) I'd go for whichever ended up being more readable.
Making code clean and maintainable is usually more important (at a
micro level) than making it perform absolutely as fast as it can.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
AddThis Social Bookmark Button