I have a simple class which has a ToString implemented which I am happy with the content. I am trying to decide what is the (most) correct way by seeing if there are any pro's/con's for the various options.
For the example below:
- Class:
Astronaut - Variable of type
Astronaut:person
Options that I am just snow balling here:
string result = person == null ? "Unknown Astronaut" : person.ToString();string result = person.ToString() ?? "Unknown Astronaut";string result = (person ?? "Unknown Astronaut").ToString();string result = person ?? (object)"Unknown Astronaut";
My views on those are
- Very verbose & I don't need that level of verbosity.
- Much better than 1 but the
ToStringfeels ugly plus worried of exceptions in thatToStringcode. - This seems popular (here & here) but I am not sure it will work. Won't the compiler complain about a
string& aAstronauttype not being the same type and thus can not be used in a coalese. - This is the one I am happiest with now, but it means a box &
ToStringshouldpersonbe null.
In summary:
- Any pro's/con's to any of the above?
- Any options you can think of?