Is there a simple way of doing the following:
String s = myObj == null ? "" : myObj.ToString();
I know I can do the following, but I really consider it as a hack:
String s = "" + myObj;
It would be great if Convert.ToString() had a proper overload for this.
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.
I disagree with that this:
String s = myObj == null ? "" : myObj.ToString();
is a hack in any way. I think it's a good example of clear code. It's absolutely obvious what you want to achieve and that you're expecting null.
UPDATE:
I see now that you were not saying that this was a hack. But it's implied in the question that you think this way is not the way to go. In my mind it's definitely the clearest solution.
Even though this is an old question and the OP asked for C# I would like to share a VB.Net solution for those, who work with VB.Net rather than C#:
Dim myObj As Object = Nothing
Dim s As String = If(myObj, "").ToString()
myObj = 42
s = If(myObj, "").ToString()
Unfortunatly VB.Net doesn't allow the ?-operator after a variable so myObj?.ToString isn't valid (at least not in .Net 4.5, which I used for testing the solution). Instead I use the If to return an empty string in case myObj ist Nothing. So the first Tostring-Call return an an empty string, while the second (where myObj is not Nothing) returns "42".
With an extension method, you can accomplish this:
public static class Extension
{
public static string ToStringOrEmpty(this Object value)
{
return value == null ? "" : value.ToString();
}
}
The following would write nothing to the screen and would not thrown an exception:
string value = null;
Console.WriteLine(value.ToStringOrEmpty());
It would be great if Convert.ToString() had a proper overload for this.
There's been a Convert.ToString(Object value)
since .Net 2.0 (approx. 5 years before this Q was asked), which appears to do exactly what you want:
http://msdn.microsoft.com/en-us/library/astxcyeh(v=vs.80).aspx
Am I missing/misinterpreting something really obvious here?
string s = String.Concat(myObj);
would be the shortest way I guess and also have neglible performance overhead. Keep in mind though it wouldn't be quite clear for the reader of the code what the intention is.
I might get beat up for my answer but here goes anyway:
I would simply write
string s = ""
if (myObj != null) {
x = myObj.toString();
}
Is there a payoff in terms of performance for using the ternary operator? I don't know off the top of my head.
And clearly, as someone above mentioned, you can put this behavior into a method such as safeString(myObj)
that allows for reuse.
actually I didnt understand what do you want to do. As I understand, you can write this code another way like this. Are you asking this or not? Can you explain more?
string s = string.Empty;
if(!string.IsNullOrEmpty(myObj))
{
s = myObj.ToString();
}
I had the same problem and solved it by simply casting the object to string. This works for null objects too because strings can be nulls. Unless you absolutely don't want to have a null string, this should work just fine:
string myStr = (string)myObj; // string in a object disguise or a null
Some (speed) performance tests summarizing the various options, not that it really matters #microoptimization (using a linqpad extension)
void Main()
{
object objValue = null;
test(objValue);
string strValue = null;
test(strValue);
}
// Define other methods and classes here
void test(string value) {
new Perf<string> {
{ "coallesce", n => (value ?? string.Empty).ToString() },
{ "nullcheck", n => value == null ? string.Empty : value.ToString() },
{ "str.Format", n => string.Format("{0}", value) },
{ "str.Concat", n => string.Concat(value) },
{ "string +", n => "" + value },
{ "Convert", n => Convert.ToString(value) },
}.Vs();
}
void test(object value) {
new Perf<string> {
{ "coallesce", n => (value ?? string.Empty).ToString() },
{ "nullcheck", n => value == null ? string.Empty : value.ToString() },
{ "str.Format", n => string.Format("{0}", value) },
{ "str.Concat", n => string.Concat(value) },
{ "string +", n => "" + value },
{ "Convert", n => Convert.ToString(value) },
}.Vs();
}
Probably important to point out that Convert.ToString(...)
will retain a null string.
Holstebroe's comment would be your best answer:
string s = string.Format("{0}", myObj);
If myObj
is null, Format places an Empty String value there.
It also satisfies your one line requirement and is easy to read.
Source: Stackoverflow.com