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
NullReferenceExceptionorInvalidCastExceptionifTis notstringandresultis null or an empty string. You can't just cast a string toT, 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.