Is this a safe and efficient way to handle the reading of null values in a DB using Generics?

StackOverflow https://stackoverflow.com/questions/1438888

  •  10-07-2019
  •  | 
  •  

Question

I have been playing with generics and was hoping I could get some feedback or suggestions on a function I created to help handle reading null values from the DB. My main concern is in the 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;
    }
Was it helpful?

Solution

Regardless of T's type, you can fall back to default(T) which will provide the default value for the given type (string.Empty, 0, false, null, etc...) :

value = default(T);

Edit: default(string) does, however, return null.

OTHER TIPS

You need also to cover other primitive data types.

value = default(T);

This return null if it is a reference type, otherwise 0, false or whatever is an appropriate default value of the given type T.

Note: default(string) is null, not string.Empty. If you want it to be String.Empty, you need to implement this as an exception.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top