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
ToString
feels ugly plus worried of exceptions in thatToString
code. - This seems popular (here & here) but I am not sure it will work. Won't the compiler complain about a
string
& aAstronaut
type 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 &
ToString
shouldperson
be null.
In summary:
- Any pro's/con's to any of the above?
- Any options you can think of?
I prefer an extension method:
public static string SafeToString(this Object obj)
{
return obj.SafeToString(string.Empty);
}
public static string SafeToString(this Object obj, string defaultString)
{
return obj == null ? defaultString : obj.ToString();
}
So to your question:
string result = person.SafeToString("Unknown Astronaut");
Create a static ToString
method and just call it like:
string result = Astronaut.ToString(person);
Best way to factor out common code.
I remember a design patterns book telling me about some object that you instantiate for the sole purpose of filling in null objects. They would return things like the empty string for name, or 0 for length, and so on. Doesn't sound like a bad idea.
You could also implement it as a static method of the Astronaut
class:
String result = Astronaut.getName(person);
You could also place a static method in the class that converts an Astronaut to string or returns "Unknown astronaut" if the argument was null.
In a similar vein, you could make it an extension method and call it directly on a variable of that type, even if it's null.
精彩评论