Which coding style do you prefer:
object o = new object();
//string s1 = o ?? "Tom"; // Cannot implicitly convert type 'object' to 'string' CS0266
string s3 = Convert.ToString(o ?? "Tom");
string s2 = (o != null) ? o.ToString() : "Tom";
s2 or s3?
Is it possible to make it shorter? s1 does not obviously work.
In this case, I think my preference would be:
Or:
Depending on whether or not
ois really expected to be astringor not. Either way, I prefer these because they better express what’s being done, and don’t pass this through an unnecessary conversion ifois already astring.As a general rule, I prefer whichever is clearer and/or actually works. When working with strings, I often need to write something like this instead:
…which can’t really be done at all with the null-coalescing operator. On the other hand, if I’m trying to coalesce a large number of values, it’s about 500 times better:
Try writing that with the ternary operator instead.
If the difference is not this dramatic, if it’s just going to be a couple of characters on one line of code, it really doesn’t matter, just use whatever you’re comfortable with.