Esteban
Esteban

Reputation: 3139

C# Generic return value

I'm doing a configuration provider, and in my service layer I have this:

public string GetValue(string key)
{
    return _ctx.Configurations.SingleOrDefault(q => q.Key == key).Value;
}

But how can I get the value in it's original type, I would like to do it like this:

public T GetValue<T>(string key)
{
    return (T)(object)_ctx.Configurations.Single(q => q.Key == key).Value;
}

As pointed out here: https://stackoverflow.com/a/9420236/544283, it will be an abuse of generics... I can live with that.

Since I know the type I could just cast the value outside the method, and treat it inside the method as a string, but I'd like to avoid that.

Upvotes: 3

Views: 2064

Answers (1)

Justin Niessner
Justin Niessner

Reputation: 245429

As long as you're sure that the cast will not fail, you could use:

var value = _ctx.Configurations.Single(q => q.Key == key).Value;
return (T)Convert.ChangeType(value, typeof(T));

If you want to be safe, you should do some additional checking to ensure that the value can actually be cast to the desired type.

Upvotes: 7

Related Questions