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.
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?
Sure, just add in some code like this:
if(typeof(TReturnType) == typeof(int))
{
var number = (int)returnValue;
//Validate your output
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.