3

I need to create a generic method which returns any type.

my code as follows

//my callee method 
public T getVal<T>(string key)
{
    string result = ConfigurationManager.AppSettings[key].ToString();
    return string.IsNullOrEmpty(result) ? (T)(object)result : default(T);
}

// and my caller's
getval<string>("somekey");
getval<int>("somekey1");
getval<bool>("somekey2")

the above call's works fine.. But, My requirement is I need set default type (eg: string) to the callee method.

eg: getval("somekey"); // callee should consider T as string by default and returns string type.
getval<int>("somekey2") //this is a normal call to the same callee which returns int type
1
  • That method does not work fine: you'll get a NullReferenceException or InvalidCastException if T is not string and result is null or an empty string. You can't just cast a string to T, you'll have to convert (parse) it. You'll probably also want to invert that null-or-empty check, and consider if using generics in this case is actually useful at all. Commented Aug 2, 2016 at 9:45

1 Answer 1

9

add this overload implementation:

public string GetVal(string key)
{
    return GetVal<string>(key);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks to Lee for that fix! overload, not override XD
thanks for quick response. But i need to use same generic method which should consider string as default if i don't mention.
This overload takes care of that! should you mention a type using <T>, the generic implementation will be called, otherwise, this implementation will be called and will call the generic implementation with string as T. should you wish other logic to be used if not type is specified, change this overload. To the best of my knowledge, you cannot set a default T type for generic methods,

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.