Coming from an old-school C background I have to admit that I write my code in a very non-OO way and there are certain aspects of C# especially that I hadn't really got into using. One such aspect was
C# Properties.
For those unfamiliar with Properties, they basically replace your Public member variables with a more configurable way of accessing or setting them.
When I first started writing my game engine (over 18 months ago) C# was completely new to me and thus I didn't use any Properties at all, most of my classes had a bunch of Public variables and various functions for updating things after variables had been changed.
I've spent quite a bit of time cleaning up old code and rewriting some horrible hacks and my Camera class stood out as one which could make use of some Properties.
I was creating a function which moved the camera from one point to another, and also changed direction so I could smoothly move from one static camera point to another.
To do this in my old Camera class I would've had to do it this way:
camera.position = newPosition;
camera.direction = newDirection;
So, I did that and the results weren't what I expected. What I'd forgotten is that I then should've rebuilt the camera's view matrix:
camera.UpdateViewmatrix();
So I then decided I might aswell replace my public Vector3 position with a Property:
public Vector3 Position
{
get{ return position; }
set{ position=value; UpdateViewMatrix(); }
}
private Vector3 position;
Now, if I update camera.Position it will automatically generate a brand new view matrix for the camera. Another use for Properties is validating the input, if the value is out of range or invalid then you can choose not to update the variable, for example:
public int OnlyPositive
{
get{ return onlyPositive; }
set{ UpdatePositive( value ); }
}
private int onlyPositive;
void UpdatePositive( int value )
{
if( value >= 0 )
{
onlyPositive = value;
}
}
Here we can selectively choose to use or ignore any values that we try to set the variable to. There are only certain situations where this is handy but every now and then you will find yourself in such a situation.
Now, my advice to those who look at Properties and think, why? Use them! There must've been about thirty public member variables that I've now replaced with Properties because something else can automatically be updated when I change their values. It's incredibly handy and means less code in your actual game or program classes!
If you found this post helpful please leave a comment below: