Confirm Property Value

So, I heard that checking the value in a property is like:

//dummy example, let assume that I want my value without dots public string MyProp { set { if(value.Contains('.')) throw new ArgumentException("Must not contain '.'", "value"); } } 

wrong, and I have to avoid it.

But in the old days I was told that this is a good way. We can use encapsulation, there is only one place to check, DRY, etc.

What happened to my little example?

+8
c # encapsulation dry
source share
4 answers

There is nothing wrong with throwing exceptions into a property setting tool. But you must throw an ArgumentException , and also actually set the value of the property!

 private string _myprop; public string MyProp{ set{ if(value.Contains('.')) throw new ArgumentException("Must not contain ."); this._myprop=value; } get { return this._myprop; } } 

From an article on best practices on MSDN :

Property references must be simple operations without any preconditions. If the receiver can throw an exception, consider redesigning the property as a method. This recommendation does not apply to indexers. Indexers may throw exceptions due to invalid arguments.

It is valid and permissible to exclude exceptions from the property setting tool.

+10
source share

Here is a good overview from a previously asked stack overflow question:

C # add check on setter method

0
source share

There are also some similar questions on SO.

You should be as light as possible. And if the setters throw an error, that's fine, but again, you can move it to a function. Things can get messy.

AVOID throw exceptions from getters properties. Real estate should be simple operations and should not have preconditions. If getter can throw an exception, it should probably be redesigned by the method.

Best Practices: Exclusion of Exceptions to Properties

Which exception is selected from the property setting tool?

0
source share

Note: Recommendations: an exception to properties to explain and discuss why throwing exceptions to properties is bad.

Admittedly, this post talks about property assets.

Setters usually see consumers as simply setting a private field hidden by this property, and perhaps doing some extra things as needed, exceptions are unexpected behavior, and can you imagine what each set statement needs to be enclosed inside a try block?

Although this can be taken as a guide, this is a guessing nightmare for developers, and the validation logic should be contained in a separate method and then called from the property, if necessary.

If you need validation or special behavior when setting properties, you should use the set method, for example. SetMyProp(string value) , since it makes a difference for it, that this can lead to an exception, etc.

If you use properties for something like a WPF model, you should use the built-in WPF validation for the data instead.

-2
source share

All Articles