C#: How can I add a precondition to a property while using the 'default' storage?

StackOverflow https://stackoverflow.com/questions/11809406

  •  24-06-2021
  •  | 
  •  

سؤال

Imagine a default property:

class Positive {
  public int Value { get; set; }
}

I would like to add a precondition: that the set value can only be positive. Is it possible to do that without adding the member-variable boilerplate?

  public int Value { get;
     set {
        if(value < 0) throw new ArgumentOutOfBoundsException();
        // continue doing 'the default thing'
        // instead of `value_=value`, mirrored by a change in the
        // get, and adding the `int value_` member variable
     }
  };
هل كانت مفيدة؟

المحلول

No, you need to explicitly declare the property in order to do what you need. Automatically implemented properties are just shorthand for the longer syntax anyhow, so in order to add additional logic to the get or set you must code them by hand.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top