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

I have several procedures, for simplicity, look like this:

public string FetchValueAsString(string key) public int FetchValueAsInteger(string key) public bool FetchValueAsBoolean(string key) public DateTime FetchValueAsDateTime(string key) 

I know that I can only have one method that returns the type of an object and just does the conversion, but I wonder if there is a way that I can just call one method and somehow use generics to determine the return value .. . perhaps?

+4
source share
3 answers
 public static T FetchValue<T>(string key) { string value; // logic to set value here // ... return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture); } 
+12
source

I assume you are writing code in C #. If you are then you can do what you are talking about:

 public T FetchValueAsType<T>(string key) 

Then you invoke the version as follows:

 FetchValueAsType<int>(key); 

At the same time, the System.Convert class provided by the framework works just as well and has similar syntax. You can find the msdn article here: http://msdn.microsoft.com/en-us/library/system.convert.aspx

+2
source

It is possible, but not knowing the implementation of the method, it is difficult to say if there is something that can be obtained, or if it is really / easily implemented as a general one.

Anyway:

 public T FetchValue<T>(string key) 

- this is what you want to do.

+1
source

All Articles