Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generic return value

Tags:

c#

generics

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.

like image 425
Esteban Avatar asked Dec 01 '25 09:12

Esteban


1 Answers

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.

like image 164
Justin Niessner Avatar answered Dec 03 '25 00:12

Justin Niessner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!