tags:

views:

121

answers:

2

Hello to all,

We've created a generic method like so:

public TReturnType GetValue(string key)
{
   var configurationParameter = (from cp in _repository.ConfigurationParameters
        where cp.ConfigurationParameterKey == key
        select cp).FirstOrDefault();

   var returnValue (TReturnType)Convert.ChangeType(configurationParameter.ConfigurationParameterValue, typeof (TReturnType));
   return returnValue;
}

Now, we would like to put some error handling in this method so that in case we're expecting a numeric type we can do, for example, an int.TryParse(returnValue, out myNewInt). Of course to be able to do that we would have to be able to determine the type of TReturnType within the method.

Is there a way to do this?

Thanks for all of your help. Regards.

+2  A: 

Sure, just add in some code like this:

if(typeof(TReturnType) == typeof(int))
{
    var number = (int)returnValue;
    //Validate your output
}
Jake Pearson
Oh my God !!! This was so simple is absolutely embarrassing. I definitely need to go home now.Thank you.
Sergio Romero
+3  A: 

Sure, but you should consider whether or not this is a good idea. You can always say

if (typeof(T) == typeof(int)) whatever

But doing so is a bit of a bad code smell. The whole point of generics is to be generic. If you have special-purpose code for when T is an integer, then why not simply add another method that handles exactly the integer case?

Eric Lippert
I've done this on a generic collection that supports 3 kinds of ids: strings, ints, and guids. Anything else would throw a not implemented exception.
Jake Pearson
Better to just have three methods then. Make your generics *generic*, that's why we called them *generics*.
Eric Lippert
You're right, I was probably being lazy.
Jake Pearson