C # change getter / setter but keep short form

I need to do a little check in C # setter - check if a property is an empty string. Right now I am done with a structure like this:

        private string property;
        public string Property
        {
           get
           {
              return property;
           }
           set
           {
              if (value.IsNotEmpty())
              {
                   property = value;
              }
           }
        }

      

Instead

public string Property { get; set; }

      

6 lines instead of 1. Is there a way to insert the logic but keep it concise and elegant?

+3


source to share


4 answers


Not

Auto-properties (or "short form") can have access modifiers, but not logic. You are stuck with the code you have.



One thing you can do is encapsulate yours string

into an object that allows implicit conversion from string (and to string), and validates IsNotEmpty

before assigning a base value. Also not the most elegant solution, but it will probably save you syntactic sugar.

+5


source


No, there is no syntactic sugar for such cases (at least until C # 5.0 - current for 2014).

You can format them differently and use ?:

instead if

if it looks good enough to you:



    public string Property
    {
       get { return property; }
       set { property = value.IsNotEmpty() ? value: property;}
    }

      

+4


source


This is not exactly what you are asking, but perhaps you can use DataAnnotations to avoid empty string. Something like this, in which case a validation exception is thrown if the property is null, an empty string (""), or contains only whitespace characters.

  [Required]
  public string Property { get; set; }

      

+2


source


You can always do it like this.

It is compact but offers no performance gain by doing it this way.

    private string property;
    public string Property { get { return property; } set { if (value.IsNotEmpty()) property = value; } }

      

+1


source







All Articles