Using Generics vs Passing System.Type as argument?

K

Kenneth Baltrinic

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);
...
}
}
 
V

VJ

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
 
J

Jon Skeet [C# MVP]

VJ said:
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..

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.
 
V

VJ

Very true Jon. Also the more hirearchy you introduce, the more tough it
becomes to maintain code. Which is also a problem.

VJ
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top