Is it possible to validate c # properties in the setter?

  • one
    Yes, it is intended for this. You can also read: msdn.microsoft.com/ru-ru/library/ms229006.aspx . Naturally, validation should be within reason, i.e. In a DB, for example, it is not necessary to climb in a setter. - kmv
  • @ kmv, why not get into the database? - Ares
  • one
    Because the setter must be fast. If you have it fundamentally slow, then instead of a setter, methods are usually made, for example SetSomeProperty(SomeType newValue) , which implies a long operation. - Monk
  • 3
    A @ or4uk programmer may not expect that accessing a property suddenly causes an error of access to the database, or simply performs lengthy operations. Because properties for the programmer look more like fields, not methods. - kmv
  • @ monk, well, he will not be so fast from the fact that I bring the logic to the method - Ares

1 answer 1

Removed from comments.


Yes, validation of the assigned value with subsequent generation of an exception in the setter is allowed.

Refer to the famous book "Framework Design Guidelines. Conventions, Idioms, and Patterns For Reusable .NET Libraries" , section 5.2:

It is OK to set the property setter. It is very important that it is a mismatch between the value and the array element type.

Microsoft quotes this book here word for word. By the way, it is not recommended to generate exceptions in the getter.

But J. Richter in "CLR via C #" (Ch. 10 "Properties") expresses a negative attitude to properties, indicating that they often have unexpected behavior for the developer:

Personally, I don’t like properties and I would be happy if Microsoft decided to remove their support from the .NET Framework and related programming languages. The reason is that properties look like fields, being essentially methods . This creates unthinkable confusion. Faced with a code that seems to refer to a field, the developer habitually assumes the existence of a multitude of conditions that are not always met when it comes to a property. [...] A property, being essentially a method, can throw exceptions, and there are no exceptions when referring to exception fields. [...] The property-method can be executed for a rather long time, while calls to fields are executed instantly.

You probably shouldn't completely abandon properties, but it is necessary to control the complexity of their logic wisely. Adding in the setter checks for null, checks for a range of valid values, etc. with the generation of an exception would be a good idea And to access the database properties, perform lengthy calculations, start and block threads, etc., no longer.

If you still need to perform additional actions, convert your property to a method.

In other words, the property should not produce actions that violate the principle of least surprise (this principle belongs to the user interface, but it is also fully applicable to the public API).