I was reading here about creating immutable classes in C#. It was suggested I make my classes this way for real immutability:
private readonly int id;
public Person(int id) {
this.id = id;
}
public int Id {
get { return id; }
}
I understand that, but what if I wanted to do some error checking, how can I throw an exception? Given the following class, I can only think to do it this way:
private readonly int id;
private readonly string firstName;
private readonly string lastName;
public Person(int id,string firstName, string lastName)
{
this.id=id = this.checkInt(id, "ID");
this.firstName = this.checkString(firstName, "First Name");
this.lastName = this.checkString(lastName,"Last Name");
}
private string checkString(string parameter,string name){
if(String.IsNullOrWhiteSpace(parameter)){
throw new ArgumentNullException("Must Include " + name);
}
return parameter;
}
private int checkInt(int parameter, string name)
{
if(parameter < 0){
throw new ArgumentOutOfRangeException("Must Include " + name);
}
return parameter;
}
Is that the correct way of doing it? If not, how would I accomplish throwing exceptions in immutable classes?