Or: How to check for null everywhere and nowhere.
Do you run into this code a lot?
if (Locations == null) Locations = new List<Vector2>();
// Followed by a bunch of code that uses Locations.
I used to.
I would use the same field in six different places and have to check and ensure it wasn't null in each place.
Here's something I like to do:
List<Vector2> _locs;
List<Vector2> Locations
{
get { return _locs ?? (_locs = new List<Vector2>()); }
}
The first two lines are clear enough. _locs is the backing field to Locations, which in turn is a property.
The getter for that property uses a feature of C# that is less well-known: the null coalescing operator. (That's the ?? in the getter).
Basically, the NCO says "return the thing on the left unless it's null, in which case, return the thing on the right."
Since assignment in C# returns the result of the assignment, all you have to do to treat an assignment like a value is wrap it in parenthesis.
So we return one of two values: the backing field or, if the backing field is null, the result of initializing the backing field.
This is a form of lazy initialization. Locations doesn't exist until we use it, at which point it magically pops into existence.
More to the point, we move the null test into the property itself. It doesn't pop up in six different methods; it's in one place.
In terms of performance, no. You want to initialize your list once before you use it, and access it directly. A property is a function in disguise and takes three or four times as long to access than a field. That said, if you are writing a game and find that accessing Location is causing a performance drop, it's easy to rewire it behind the scenes. Just replace the property with a field of the same name and make sure it's initialized in the constructor.
I go with this simply because, as a one-man team, I shouldn't be writing games that require a level of performance where this will be an issue.
In terms of Object Oriented doctrine, this may or may not be Evil. I've seen debate on the topic. Neither side provided anything I would consider an argument in the debates I've seen, which leads me to believe it's fairly innocuous. That said, I am not a proponent of OOP, so it's probably a horrible technique that will get you fired and/or bring down your entire code base, and I just don't know it. Use at your own risk.