Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# modify getter/setter but keep the short form

Tags:

c#

getter

setter

I need to do a minor check in C# setter - check if property is an empty string. Right now I ended up with structure like that:

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

Instead of

public string Property { get; set; }

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

like image 843
anyaeats160carrots Avatar asked Oct 24 '14 00:10

anyaeats160carrots


4 Answers

No

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

One thing you could do is to encapsulate your string in an object that allows for an implicit cast from string (and to string), and checks IsNotEmpty before assigning to a underlying value. Also not the most elegant solution, but it would probably allow you to keep the syntactic sugar.

like image 121
BradleyDotNET Avatar answered Sep 30 '22 01:09

BradleyDotNET


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

You can format them differently and use ?: instead of if if it looks nice enough to you:

    public string Property
    {
       get { return property; }
       set { property = value.IsNotEmpty() ? value: property;}
    }
like image 36
Alexei Levenkov Avatar answered Sep 30 '22 00:09

Alexei Levenkov


It's not exactly what you ask, but perhaps you can use DataAnnotations, for not allowing an empty string. Something like this, in this case a validation exception is raised if the property is null, an empty string (""), or contains only white-space characters.

  [Required]
  public string Property { get; set; }
like image 24
Esteban Elverdin Avatar answered Sep 30 '22 02:09

Esteban Elverdin


As of C# 7, properties support arrow syntax, making the following possible:

private string property;
public string Property
{
    get => property;
    set => property = value.IsNotEmpty() ? value : property;
}
like image 44
Andii Avatar answered Sep 30 '22 00:09

Andii