I do agree with Mark Seeman's notion that Automatic Properties are somewhat evil as they break encapsulation. However I do like the concise syntax, readability and convenience they bring.
I quote:
public string Name { get; set; }
The problem with the code snippet isn’t that it contains too much ceremony. The problem is that it breaks encapsulation. In fact
“[…] getters and setters do not achieve encapsulation or information hiding: they are a language-legitimized way to violate them.”
James O. Coplien & Gertrud Bjørnvig. Lean Architecture. Wiley. 2010. p. 134.
Most of the time, adding a non-null guard clause is good enough for a property setter and I would like to know if there is a better way of doing it than one of the below. By better, I mean in a more concise/less repetitive way.
Using Code Contracts:
private string _username;
public virtual string Username
{
get { return _username; }
set
{
Contract.Requires(value != null);
_username = value;
}
}
Using vanilla .NET:
private string _username;
public virtual string Username
{
get { return _username; }
set
{
if (value == null) throw new ArgumentNullException("Username");
_username = value;
}
}