Checking nulls for the generic types

74 views Asked by At

I wanted to create a function, which will check the value of the parameter, if it's null it should set the value based on type of the parameter, else it should just return the value as it is.

Here what i have tried.

public static T ConvertNull<T>(T obj)
{
    if (String.IsNullOrEmpty(obj.ToString()))
    {
        HttpContext.Current.Response.Write("COMING IN");
        if (typeof(T) == typeof(Int32))
        {
            return (T)Convert.ChangeType(0, typeof(T));
        }
        else if (typeof(T) == typeof(DateTime))
        {
            return (T)Convert.ChangeType(DateTime.Now, typeof(T));
        }
        else
        {
            return (T)Convert.ChangeType(String.Empty, typeof(T));
        }
    }
    else
    {
        HttpContext.Current.Response.Write("ELSE");
        return obj;
    }
}

But the problem is it always goes in ELSE section and returns Junk value.

Can anyone tell me what's wrong with the above function.

2

There are 2 answers

5
D Stanley On

String.IsNullOrEmpty(obj.ToString()) is very rarely going to be true. THe only thing I can think of that will generate an empty string vi ToString() is another empty string. In fact unless ToString() has been overridden (like it has been for native types like DateTime and int, you will get the fully qualified name of the object.

maybe you want

if (obj == default(T))

?

0
Servy On

If you have a nullable type that you want to replace with some value in the event that it is null, and return the existing value in the event that it is not-null, there is alerady an existing operator that does this, the ?? operator:

int? i = null;  //note of course that a non-nullable int cannot be null
int n = i ?? 0; //equals zero

string s = null;
string s2 = s ?? ""; //equals an empty string

string s3 = "hi";
string s4 = s3 ?? ""; //equals "hi"

Conveniently the ?? operator will not even compile in the event that the first operand's type is not nullable.