views:

159

answers:

2

What is the best way to make a class property "Write Once, Read Many" such that you can only set the property once?

I know that I could pass all the properties in the constructor and make them ReadOnly, but in cases with a lot of properties I don't want a constructor that has 20+ arguments.

Also, I realize I can "roll my own" setters, but having to do that for every property seems like a bunch of redundant coding.

Is there a clean way to do this in VB 2008 .NET 3.5?

A: 

The "cleanest" way would be not to do it at all and use auto properties. I fail to see the need for it too. Is it really that important that they can only be written once? If so I would definitely go with a constructor that takes values for all the properties as parameters.

klausbyskov
An example of a property I would use this for is an "ID" property, that is a unique identifier for the class. It isn't life or death, but it would ensure that the "ID" didn't get changed by other code.I'm not all that familiar with Auto Properties, other than knowing that they aren't supported in the VB version I'm using. Is it possible to make them Write Once Read Many?
Casey
+1  A: 

A Write Once Property is never "clean".

I'd recommend to create a builder/factory class to avoid the 20 param CTor. (Yes, I know it is quite some typing)

Similar discussion here: http://stackoverflow.com/questions/1079292/should-i-use-set-once-variables/1079316#1079316

[edit] Furthermore, even if you insist I don't see another option than rolling your own setters, which is a lot of typing, too.

peterchen
Thanks. The post you linked explains a lot, and I agree with your "Least surprises" principle. Using a builder may be the best solution.
Casey