My requirement is to create a common C# method which takes a numeric datatype (including nullable) as argument and returns the value as string or "NULL" if the variable is null or 0.
The main purpose of this method is to generate an INSERT SQL statement, where if a parameter value is 0 it should insert a NULL in the database.
I have tried the following code but not very sure if it can handle all numeric data types in C#. i.e. int
, int?
, short
, short?
, double
, double?
I ran some examples and it seems to work fine, but I don't want to miss something basic and cause issues in production environment.
public string GetNumericForSQL<T>(object obj, string textIfZero = "NULL")
{
string res = "NULL";
//Check if obj is Nullable numeric data type
if (default(T) == null)
{
string temp = (obj ?? 0).ToString();
if (temp == "0")
res = textIfZero;
else
res = temp;
}
else
{
res = obj.ToString();
}
return res;
}