Does this smell?
I have a few properties you can only set once. They can be set at any time during the objects existence and can not be undone.
I implement then like
I think the design would be more clear to the caller if such values are passed to the constructor, and exposed as read-only properties instead. If the value can't be set at construction time, perhaps it could be appropriate to throw an exception if trying to set the value again:
private FooThingy _foo;
public FooThingy Foo
{
set
{
if (null == _foo) { _foo = value; }
else { throw new WhatEverThatFitsException(); }
}
get { return _foo; }
}
Just to be very clear: I do not in any way promote the use of set-once properties; the code sample only show the approach that I might use, should the value not be available at construction time of the object for whatever reason. That said; I have never come across that situation in any of the projects I have been involved in.
if FooThingy is a value object like an int it will be 0 initialized instead of null. For the rest it looks okay
Make them readonly and set them in the constructor.
I agree with Fredrik, readonly would make more sense. This way you could only declare your variable in the constructor (or as part of the declaration). I think doing what your doing isnt instantly clear that this is what you want to achieve.
Check out this MSDN page.
It's hard to tell from this toy example, but it sounds like _foo
is relatively important to the existence of this object. In that case, it should almost certainly be a readonly property which is initialized at creation time, and not have any public setter. Favor immutable objects wherever possible; it makes your life much simpler!
I would suggest setting them on construction, and therefore making the setters private. That seems like a more sensible way.
If you are going to do it that way, throw some sort of Exception. At least let the developer know you didn't set their values rather than ignoring it silently.