I want to enforce on my code base immutable rule with following test
[TestFixture]
public class TestEntityIf
{
[Test]
public void IsImmutable()
{
var setterCount =
(from s in typeof (Entity).GetProperties(BindingFlags.Public | BindingFlags.Instance)
where s.CanWrite
select s)
.Count();
Assert.That(setterCount == 0, Is.True, "Immutable rule is broken");
}
}
It passes for:
public class Entity
{
private int ID1;
public int ID
{
get { return ID1; }
}
}
but doesn’t for this:
public class Entity
{
public int ID { get; private set; }
}
And here goes the question “WTF?”
A small modification to answers posted elsewhere. The following will return non-zero if there is at least one property with a protected or public setter. Note the check for GetSetMethod returning null (no setter) and the test for IsPrivate (i.e. not public or protected) rather than IsPublic (public only).
Nevertheless, as pointed out in Daniel Brückner’s answer, the fact that a class has no publicly-visible property setters is a necessary, but not a sufficient condition for the class to be considered immutable.