Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to set a default function for getters and setters?

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading