I’ve been wondering about this: would you support using simply an object as a parameter in your method? My reason behind doing this would be overloading. Currently, I’m trying to create a method that caters to many different datatypes: string, decimal, DateTime… the list goes on.
It’s getting a bit messy though, so I was thinking of doing the following
public void GenericMethod(object val)
{
if (val is string)
// process as string
else if (val is decimal)
// process as decimal
else if (val is DateTime)
// do something for dt
else
// ...
}
What do you think of such a method? Would it incur unnecessary overhead? (during type checking) Have you implemented it? Tell me…
EDIT: Yeah, and just a sidenote, I’m kinda familiar with overloading. But it gets a little annoying when there are like more than 10 overloads…
Very rarely. If there’s a fixed set of types which are properly supported – and you’ll throw an exception otherwise – then I’d use overloads.
If you can actually accept any type, and you’ll handle a not-specially-supported type in some well-known way, then it’s okay to accept
object. That’s what LINQ to XML does all over the place, and the result is a very clean API. I’d do it very carefully though – it’s rarely a good idea.And yes, there’d be an overhead. I wouldn’t usually make that the basis of the decision though – the overhead will be small enough to be negligible in most cases. Design your API as cleanly as you can, then work out whether it’s going to cause a bottleneck.