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();
Use "+ string.Empty" or "?.ToString() ?? string.Empty" for a nullable object
java - Convert null object to String - Stack Overflow
c# - How to do ToString for a possibly null object? - Stack Overflow
C#, how can someone create a null string?
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.
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# 6.0 Edit:
With C# 6.0 we can now have a succinct, cast-free version of the orignal method:
string s = myObj?.ToString() ?? "";
Or even using interpolation:
string s = $"{myObj}";
Original Answer:
string s = (myObj ?? String.Empty).ToString();
or
string s = (myObjc ?? "").ToString()
to be even more concise.
Unfortunately, as has been pointed out you'll often need a cast on either side to make this work with non String or Object types:
string s = (myObjc ?? (Object)"").ToString()
string s = ((Object)myObjc ?? "").ToString()
Therefore, while it maybe appears elegant, the cast is almost always necessary and is not that succinct in practice.
As suggested elsewhere, I recommend maybe using an extension method to make this cleaner:
public static string ToStringNullSafe(this object value)
{
return (value ?? string.Empty).ToString();
}
string.Format("{0}", myObj);
string.Format will format null as an empty string and call ToString() on non-null objects. As I understand it, this is what you were looking for.
Don't all strings get initialized as an empty string? And if they get initialized as null...why... What kind of design decision is that.
The editor forces me to use string? temp = Console.ReadLine()
because if I use string it's possible it can be null. How?? Even if they just press enter it still would just be an empty string. An empty string isn't null, it's just empty. I don't see how someone could pass the program null as a value.
EDIT: Case closed
After reviewing my previous answer, it seems a complete overhaul of my previous answer is necessary. I was way over complicating it, as the short answer is that these are standards-specified special cases.
The specification for String() (String used as a function):
15.5.1.1 String ( [ value ] )
Returns a String value (not a String object) computed by ToString(value). If value is not supplied, the empty String "" is returned.
The ToString function (that exists internally, not in userland) is defined as follows (9.8):
"The abstract operation ToString converts its argument to a value of type String according to Table 13"
Argument Type | Result
Null | "null"
Undefined | "undefined"
This means that String(null) and String(undefined) go into this special table of types and just return the string values valued "null" and "undefined".
A user-land pseudo-implementation looks something like this:
function MyString(val) {
if (arguments.length === 0) {
return "";
} else if (typeof val === "undefined") {
return "undefined";
} else if (val === null) {
return "null";
} else if (typeof val === "boolean") {
return val ? "true" : "false";
} else if (typeof val === "number") {
// super complex rules
} else if (typeof val === "string") {
return val;
} else {
// return MyString(ToPrimitive(val, prefer string))
}
}
(Note that this example ignores the constructor case (new MyString()) and that it uses user-land concepts rather than engine-land.)
I got a bit carried away and found an example implementation (V8 to be specific):
string.js:
// Set the String function and constructor.
%SetCode($String, function(x) {
var value = %_ArgumentsLength() == 0 ? '' : TO_STRING_INLINE(x);
if (%_IsConstructCall()) {
%_SetValueOf(this, value);
} else {
return value;
}
});
macros.py:
macro TO_STRING_INLINE(arg) = (IS_STRING(%IS_VAR(arg)) ? arg : NonStringToString(arg));
runtime.js:
function NonStringToString(x) {
if (IS_NUMBER(x)) return %_NumberToString(x);
if (IS_BOOLEAN(x)) return x ? 'true' : 'false';
if (IS_UNDEFINED(x)) return 'undefined';
return (IS_NULL(x)) ? 'null' : %ToString(%DefaultString(x));
}
The NonStringToString (which is essentially what is of interest), is luckily defined in psuedo-JS-land. As you can see, there is indeed a special case for null/true/false/undefined.
There is probably just some extra checks and handling for special cases like null and undefined.
MDN says:
It's possible to use String as a "safer" toString alternative, as although it still normally calls the underlying toString, it also works for null and undefined.