I want to make a generic function for doing some operations, like:
ConvertValue<T>(string value)
If T is int then the function will convert the value to int and return the result.
Similarly, if T is boolean, the function will convert the value to boolean and return it.
How to write this?
Something like this?
You can then use it like this:
Edit:
You can even do this more generic and not rely on a
stringparameter provided the typeUimplementsIConvertible– this means you have to specify two type parameters though:I considered catching the
InvalidCastExceptionexception that might be raised byConvert.ChangeType()– but what would you return in this case?default(T)? It seems more appropriate having the caller deal with the exception.