Home > Software engineering >  Is there a way to set a default function for getters and setters?
Is there a way to set a default function for getters and setters?

Time:11-08

I was wondering if there is a way to set a default function for a getter or a setter. For example, let's say I have this:

public class MyClass
{
    public bool IsDirty {get; private set; } = false;

    private string _property;
    public string Property1 
    { 
        get 
        { 
            return _property1;
        } 
        set
        {
            if (value != _property1)
            {
                _property1 = value;
                IsDirty = true;
            }
        } 
    }
}

I was wondering if there was a way to do something like this:

public class MyClass
{
    public bool IsDirty {get; private set;} = false;

    MyClass.defaultSet = { if (value != !_property1) { _property1 = value; IsDirty = true; } };

    private string _property1;
    public string Property1 { get; set; }

    public string Property2 {get; set;}
    public string Property3 {get; set;}
   //...
}        

So that I don't have to do it the first way on this big class I have (~100 properties).

CodePudding user response:

You can reduce the noise by using a helper method like this

private void Set<T>(ref T field, T value)
{
  if (!Equals(value, field))
  {
    field = value;
    IsDirty = true;
  }
}

Then you can write:

public string Property1
{
  get => _property1;
  set => Set(ref _property1, value);
}

CodePudding user response:

No, this doesn't exist, for several reasons:

  1. Not every property is going to be a string, so this would need to correctly handle integers, DateTimes, Decimal, etc
  2. Primitive value types are bad enough, but then start throwing in things like Tuples, complex classes (where changing a class member is still get operation on the property itself!), delegates, etc
  3. If you reference a property by it's own name, you're creating a circular reference that will cause a StackOverflowException.
  4. Not every property is going to use the same Property name, so that part of the method is different. You'd need another keyword or argument to the set method.
  5. You need a way to exempt the someBool / IsDirty property.
  • Related