views:

32

answers:

1

When developing a class (in C# but I suppose this question is somewhat language independent) what is the correct way to deal with dependencies between properties?

For example where I want to create a property B whose value is derived in some way from the value of property A. Property B is undefined and should not be called if property A has not been set. Throwing an exception in B's getter if A has not been set hardly seems like an elegant way of handling this. Simply returning some default value from property B is not something I want to do.

One way is to enforce initialization of A through the constructor, but let's assume that a default constructor with no arguments is required so this is not an option.

+2  A: 

Throwing an InvalidOperationException in this case seems entirely proper to me:

InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments

Now granted it talks about a method rather than a property, but I think it's still fine.

If you want an example from the framework, IEnumerator.Current is specified to throw InvalidOperationException if it's called before the first element or after the last one. (C#-generated iterators don't do that in fact, but that's a different matter :)

It sounds like it's a bug in the calling code to do this... they're using the object improperly. The correct way to indicate a bug is to throw an exception.

Jon Skeet
Thanks Jon. I'll do that then, but it will be interesting to hear of any other options people may have taken.
Steve Crane