开发者

Is this the best approach using generics to check for nulls?

public static T IsNull<T>(object value, T defaultValue)
{
    return ((Object.Equals(value,null)) | (Object.Equals(value,DBNull.Value)) ?
        defaultValue : (T)value);
}

public static T IsNull<T>(object value) where T :new()
{
    T defaultvalue = new T();
    return IsNull(value, 开发者_Python百科defaultvalue);
}

Have tested, and can use against data objects, classes and variables. Just want to know if there is better way to go about this.


It looks like you're trying to duplicate the null coalesce operator:

var foo = myPossiblyNullValue ?? defaultValue;


First off, the method name is wrong. You imply that the result of the function is a boolean that is true exactly if the given value is null. In fact, that’s not the case. GetValueOrDefault might be a better name.

Secondly, you’re merely replicating the behaviour of the null coalesce operator, as mentioned by others.

Thirdly, your conditional is odd:

Object.Equals(value,null)) | (Object.Equals(value,DBNull.Value)

Why Object.Equals instead of ==? Better yet, use Object.ReferenceEquals since that makes it clear that you’re interested in reference equality. Also, you’re using the bitwise-or operator (|) which is semantically wrong in this context, although it happens to yield the right value. You want the boolean-or operator ||. (Also, inconsistency: why do you sometimes write object and other times Object?)

Finally, using type object instead of a generic type isn’t necessarily a good solution. It would be better to create overloads for generic reference and value types: this avoids boxing in the value types. It also means that you don’t have to specify the type explicitly in your second overload since it can be deduced from the method argument.


public static bool IsNull<T>(object value)
{
    return object == default(T);
}


[Edited]

The following (non-generic) should work.

    public static bool IsNull(object value) 
    {
        return value == null;
    } 

Any value type will get boxed (i.e. non-null). Ref types will just be passed by pointer.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜