static string NullToString( object Value )
{
// Value.ToString() allows for Value being DBNull, but will also convert int, double, etc.
return Value == null ? "" : Value.ToString();
// If this is not what you want then this form may suit you better, handles 'Null' and DBNull otherwise tries a straight cast
// which will throw if Value isn't actually a string object.
//return Value == null || Value == DBNull.Value ? "" : (string)Value;
}
Answer from Gareth Wilson on Stack Overflowstatic string NullToString( object Value )
{
// Value.ToString() allows for Value being DBNull, but will also convert int, double, etc.
return Value == null ? "" : Value.ToString();
// If this is not what you want then this form may suit you better, handles 'Null' and DBNull otherwise tries a straight cast
// which will throw if Value isn't actually a string object.
//return Value == null || Value == DBNull.Value ? "" : (string)Value;
}
When you get a NULL value from a database, the value returned is DBNull.Value on which case, you can simply call .ToString() and it will return ""
Example:
reader["Column"].ToString()
Gets you "" if the value returned is DBNull.Value
If the scenario is not always a database, then I'd go for an Extension method:
public static class Extensions
{
public static string EmptyIfNull(this object value)
{
if (value == null)
return "";
return value.ToString();
}
}
Usage:
string someVar = null;
someVar.EmptyIfNull();
Instead of catching the exception or putting conditions, use
String.valueOf(result.getPropertyAsString(0));
It will call toString() method of the argument and will convert it to String and if result.getPropertyAsString(0) is null, then it will change it to "null".
Although it's not a good practice, you can concatenate the null value with "" to make it a String.
For example:
String str=null;
System.out.println((str+"").length()); /// prints 4
c# - How to convert nullable int to string - Stack Overflow
Convert null.String to string
Use "+ string.Empty" or "?.ToString() ?? string.Empty" for a nullable object
c# - Why does Convert.ToString(null) return a different value if you cast null? - Stack Overflow
You can simply use the Convert.ToString() which handles the null values as well and doesn't throw the exception
string str = Convert.ToString(a)
Or using if condition
if(a.HasValue)
{
string str = a.Value.ToString();
}
Or using ? Ternary operator
string str = a.HasValue ? a.Value.ToString() : string.Empty;
If you really need the string as "Null" if a is null:
string str = a.HasValue ? a.Value.ToString() : "Null";
The Title basically says it all. If an object is not null, calling ".ToString()" is generally considered better than "+ string.Empty", but what about if the object could be null and you want a default empty string.
To me, saying this
void Stuff(MyObject? abc)
{
...
string s = abc?.ToString() ?? string.Empty;
...
}is much more complex than
void Stuff(MyObject? abc)
{
...
string s = abc + string.Empty;
}The 2nd form seems to be better than the 1st, especially if you have a lot of them.
Thoughts?
----
On a side note, something I found out was if I do this:
string s = myNullableString + "";
is the same thing as this
string s = myNullableString ?? "";
Which makes another branch condition. I'm all for unit testing correctly, but defaulting to empty string instead of null shouldn't really add another test.
using string.Empty instead of "" is the same as this:
string s = string.Concat(text, string.Empty);
So even though it's potentially a little more, I feel it's better as there isn't an extra branch test.
EDIT: the top code is an over simplification. We have a lot of data mapping that we need to do and a lot of it is nullable stuff going to non-nullable stuff, and there can be dozens (or a lot more) of fields to populate.
There could be multiple nullable object types that need to be converted to strings, and having this seems like a lot of extra code:
Mydata d = new()
{
nonNullableField = x.oneField?.ToString() ?? string.Empty,
anotherNonNullableField = x.anotherField?.ToString() ?? string.Empty,
moreOfThesame = x.aCompletelyDifferentField?.ToString() ?? string.Empty,
...
}vs
Mydata d = new()
{
nonNullableField= x.oneField + string.Empty, // or + ""
anotherNonNullableField= x.anotherField + string.Empty,
moreOfThesame = x.aCompletelyDifferentField + string.Empty,
...
}The issue we have is that we can't refactor a lot of the data types because they are old and have been used since the Precambrian era, so refactoring would be extremely difficult. When there are 20-30 lines that have very similar things, seeing the extra question marks, et al, seems like it's a lot more complex than simply adding a string.
There are 2 overloads of ToString that come into play here
Convert.ToString(object o);
Convert.ToString(string s);
The C# compiler essentially tries to pick the most specific overload which will work with the input. A null value is convertible to any reference type. In this case string is more specific than object and hence it will be picked as the winner.
In the null as object you've solidified the type of the expression as object. This means it's no longer compatible with the string overload and the compiler picks the object overload as it's the only compatible one remaining.
The really hairy details of how this tie breaking works is covered in section 7.4.3 of the C# language spec.
Following on from JaredPar's excellent overload resolution answer - the question remains "why does Convert.ToString(string) return null, but Convert.ToString(object) return string.Empty"?
And the answer to that is...because the docs say so:
Convert.ToString(string) returns "the specified string instance; no actual conversion is performed."
Convert.ToString(object) returns "the string representation of value, or String.Empty if value is null."
EDIT: As to whether this is a "bug in the spec", "very bad API design", "why was it specified like this", etc. - I'll take a shot at some rationale for why I don't see it as big deal.
System.Converthas methods for converting every base type to itself. This is strange - since no conversion is needed or possible, so the methods end up just returning the parameter.Convert.ToString(string)behaves the same. I presume these are here for code generation scenarios.Convert.ToString(object)has 3 choices when passednull. Throw, return null, or return string.Empty. Throwing would be bad - doubly so with the assumption these are used for generated code. Returning null requires your caller do a null check - again, not a great choice in generated code. Returning string.Empty seems a reasonable choice. The rest ofSystem.Convertdeals with value types - which have a default value.- It's debatable whether returning null is more "correct", but string.Empty is definitely more usable. Changing
Convert.ToString(string)means breaking the "no actual conversion" rule. SinceSystem.Convertis a static utility class, each method can be logically treated as its own. There's very few real world scenarios where this behavior should be "surprising", so let usability win over (possible) correctness.
SELECT Id 'PatientId',
ISNULL(CONVERT(varchar(50),ParentId),'') 'ParentId'
FROM Patients
ISNULL always tries to return a result that has the same data type as the type of its first argument. So, if you want the result to be a string (varchar), you'd best make sure that's the type of the first argument.
COALESCE is usually a better function to use than ISNULL, since it considers all argument data types and applies appropriate precedence rules to determine the final resulting data type. Unfortunately, in this case, uniqueidentifier has higher precedence than varchar, so that doesn't help.
(It's also generally preferred because it extends to more than two arguments)
Select ID, IsNull(Cast(ParentID as varchar(max)),'') from Patients
This is needed because field ParentID is not varchar/nvarchar type. This will do the trick:
Select ID, IsNull(ParentID,'') from Patients
You could try it like this using the ternary operator.
System.out.println(a == null ? "" : a);
Alernatively, you can use the Commons Lang3 function defaultString() as suggested by chrylis,
System.out.println(StringUtils.defaultString(a));
I would factor out a utility method that captures the intention, which improves readability and allows easy reuse:
public static String blankIfNull(String s) {
return s == null ? "" : s;
}
Then use that when needed:
System.out.println(blankIfNull(a));