I have a few procedures, for simplicity sake, look like the following:
public string FetchValueAsString(string key)
public int FetchValueAsInteger(string key)
public bool FetchValueAsBoolean(string key)
public DateTime FetchValueAsDateTime(string key)
I know I could just have one method that returns and object type and just do a conversion, but I'm wondering if there is a way I can just have one method called, and somehow use generics to determine the return value ... possible?
public static T FetchValue<T>(string key)
{
string value;
// logic to set value here
// ...
return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
}
I'm assuming you're writing code in C#. If you are then you could do what your talking about like this:
public T FetchValueAsType<T>(string key)
You would then call the version like this:
FetchValueAsType<int>(key);
That being said the the System.Convert
class provided by the framework works just as well and has similar syntax. You can find the msdn article about it here:
http://msdn.microsoft.com/en-us/library/system.convert.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With