3

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.

2
  • 1
    What type does the Value have? If the Value property is e.g. the base type for T, you could just set the where constraint for T, and then simply make the conversion without needing the object part. Commented Sep 10, 2012 at 22:00
  • Since the values are mainly string, int, bool and DateTime I think I could restrict it using where T : IConvertible. Commented Sep 10, 2012 at 22:16

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.