How to write an extension method that should check value of the object,if object is null then it should return null otherwise value{without doing casting at receiving end}.
something like...
public static object GetDefault(this object obj)
{
if (obj == null) return null;
else return obj;
}
I mean without casting can i check for null?
int? a=a.GetDefault();
ContactType type=type.GetDefault(); [For EnumType]
string s=a.GetDefault(开发者_JAVA技巧)
This should work:
public static class ExtensionMethods
{
public static T GetObject<T>(this T obj, T def)
{
if (default(T).Equals(obj))
return def;
else
return obj;
}
}
I've added a parameter def
because I expected you to want to return this default value when obj is null. Otherwise, you can always leave out the T def
parameter and return null
instead.
精彩评论