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.
String.IsNullOrEmpty(obj.ToString())
is very rarely going to betrue
. THe only thing I can think of that will generate an empty string vi ToString() is another empty string. In fact unlessToString()
has been overridden (like it has been for native types likeDateTime
andint
, you will get the fully qualified name of the object.maybe you want
?