Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One function with varying return types ... possible with Generics?

Tags:

c#

.net

generics

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?

like image 266
mattruma Avatar asked Dec 07 '22 08:12

mattruma


2 Answers

public static T FetchValue<T>(string key)
{
    string value;  
    // logic to set value here  
    // ...  
    return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);  
}
like image 141
Corin Blaikie Avatar answered Dec 09 '22 22:12

Corin Blaikie


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

like image 42
Mykroft Avatar answered Dec 09 '22 20:12

Mykroft