Is this a safe and efficient way to handle reading null values โ€‹โ€‹in a database using Generics?

I played with generics and hoped that I could get some feedback or suggestions on the function I created to help handle reading the null values โ€‹โ€‹from the database. My main problem is if statement. Is there a better way to find out if T is a string ect.? Thanks.

public static T CheckNull<T>(object value)
    {
        if ((value != null) && value.Equals(DBNull.Value))
        {
            if (object.ReferenceEquals(typeof(T), typeof(String)))
                value = string.Empty;
            else if (object.ReferenceEquals(typeof(T), typeof(Boolean)))
                value = false;
            else
                value = null;
        }
        return (T)value;
    }
+3
source share
2 answers

Regardless of the type T, you can go back to default(T), which will provide a default value for the type ( , , , etc.): string.Empty0falsenull

value = default(T);

Edit: default(string)however, returns null.

+3

.

value = default(T);

null, , 0, false - - T.

. default () null, string.Empty. , String.Empty, .

+2

Source: https://habr.com/ru/post/1717927/


All Articles