tags:

views:

212

answers:

4

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?

+8  A: 
public static T FetchValue<T>(string key)
{
    string value;  
    // logic to set value here  
    // ...  
    return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);  
}
Corin
This worked perfectly ... thanks!
mattruma
+2  A: 

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

Mykroft
+1  A: 

It's possible, but without knowing the method's implementation, it's hard to say whether there is something to be gained, or if it's truly/easily implementable as a generic.

At any rate:

public T FetchValue<T>(string key)

would be what you're looking to do.

lc
A: 

I'd recommend overriding for this. That way, you have multiple functions with the same name of wich the right one is chosen based upon the context (return type needed, arguments). Or you could use a single function, with the return type set to Object, wich is a generic type.

FrozenFire
First, you mean overloading, not overriding. Second, there's no way to overload a method with the same signature but different return types. Third, returning an object doesn't solve the problem - we need a way to choose which type we want out.
lc
-1 because you can earn a badge by deleting your first post with 3 down-votes. :)
MusiGenesis
Funny. Very funny.
FrozenFire