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

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; }

--------------Solutions-------------

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.

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.

Category:c# Time:2009-09-17 Views:1
Tags: .net c# generics

Related post

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.486 (s). 13 q(s)