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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With