开发者

C# Extension Method for Null or value

开发者 https://www.devze.com 2023-01-20 14:45 出处:网络
How towrite an extension methodthat should check valueof the object,if object is nullthen itshould return nullotherwisevalue{without doing casting atreceiving end}.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消