简体   繁体   中英

How to convert struct to NULL if value is default

How to convert struct to nullable struct if the value is default value. In the code below the EqualityComparer<T>.Default.Equals return false when variable of type int has zero value

    public static Nullable<T> ConvertToNullIfDefault<T>(this T src) where T : struct
    {
        if (EqualityComparer<T>.Default.Equals(src))
        {
            return null;
        }

        return (Nullable<T>)src;
    }

Test

    [Fact]
    public void ConvertToNullIfDefault_ReturnsNull_WhenIntegerIsDefault()
    {
        var val = default(int);

        var result = val.ConvertToNullIfDefault();

        Assert.Null(result);
    }

A better approach is to use the IEquatable<T> constraint:

    public static Nullable<T> ConvertToNullIfDefault<T>(this T src)
        where T : struct, IEquatable<T>
    {
        if( src.Equals( default(T) ) )
        {
            return null;
        }

        return (Nullable<T>)src;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM