A lot of programmers are not familiar with the term immutable when it comes to software development the terminology often confuses them. I am going to try and explain it in this post.
An immutable object is an object that once it is created none of its values should change.
A simple way to do this is to only assign to the variables of that object in the constructor so that once the object is created its variables cannot be changed:
public class GPSCoords
{
private readonly int longitude;
private readonly int latitude;
public GPSCoords(int longitude, int latitude)
{
this.longitude = longitude;
this.latitude = latitude;
}
public int Longitude
{
get { return longitude; }
}
public int Latitude
{
get { return latitude; }
}
}
You can also achieve the same goal in .NET by making the class GPSCoords a struct:
public struct GPSCoords
{
public readonly int longitude;
public readonly int latitude;
public GPSCoords2(int longitude, int latitude)
{
this.longitude = longitude;
this.latitude = latitude;
}
}
If you have worked with the string class in the .NET framework you probably didn't realize that you were working with a immutable class. So the next time someone asks you in an interview to explain the behaviour of the string class you will be able to explain it to them.
[ Currently Playing : Window in the Skies - U2 - U218 Singles (04:07) ]