Properties with non public setters sometimes make sense – until a unit test requires an object to be set up in a specific state. I don’t want to make the setter public just because of the tests, so I wrote a small helper function that can call non public setters.
The helper returns the object itself, to allow a fluent syntax inside member initialization expressions and uses a lambda to select the member (I do like compile time checking whenever it’s possible).
This is actual code I wrote last week using the helper. It’s part of a set up of an object collection used for unit tests.
Orders = new List<order> { new Order { OrderId = 983427, }.CallNonPublicSetter(o => o.StatusId, OrderStatus.Confirmed), new Order { OrderId = 18956, }.CallNonPublicSetter(o => o.StatusId, OrderStatus.Delivered) }; </order> |
The helper is implemented using reflection to access the property to bypass the protection level of the setter.
I quickly got my first favourite command: Go to File.