0

I'm looking to mark individual properties in my class as dirty.

I came across a method for marking an entire class as dirty here. This could be simplified to.

class DirtyClass
{
    private string bar;
    private int foo;

    public string Bar
    {
        get { return bar; }
        set { SetProperty(ref bar, value); }
    }

    public int Foo
    {
        get { return foo; }
        set { SetProperty(ref foo, value); }
    }

    public bool IsDirty { get; private set; }

    protected void SetProperty<T>(ref T field, T value)
    {
        if (!EqualityComparer<T>.Default.Equals(field, value))
        {
            field = value;
            IsDirty = true;
        }
    }
}

I have tried to use this code as a guide for creating a DirtyProperty class

class DirtyProperty<T> where T : class
{
    private bool isDirty = true;
    private T property;

    public bool GetIsDirty()
    {
        bool b = isDirty;

        // Reset dirty flag
        isDirty = false;

        return b;
    }

    public T GetValue()
    {
        return property;
    }

    public void SetValue(ref T value)
    {
        if (!EqualityComparer<T>.Default.Equals(property, value))
        {
            property = value;
            isDirty = true;
        }
    }
}

The dirty flag is marked as false in the GetIsDirty method as it is only ever called once per frame and will not be called by other classes outside the class that holds the DirtyProperty class. Is there a better approach to marking isDirty as false for handling multiple calls to the function?

The problem is that if I use a non reference type (such as an int) then this approach fails.

class ClassWithDirtyProperties
{
    public DirtyProperty<string> Bar;
    public DirtyProperty<int> Foo;
}

How can I improve my approach and fix this issue?

Example of how I wish to use the above class

        var c = new ClassWithDirtyProperties();
        c.Foo.SetValue(21);

......

        if (c.Foo.GetIsDirty())
        {
            // Update parameter
            SetParameter(c.Foo.GetValue());
        }
Community
  • 1
  • 1
user1423893
  • 766
  • 4
  • 15
  • 26

2 Answers2

1
class DirtyProperty<T> where T : class

this line says that T should be a reference type. If you want to allow int as a template then remove the where part. So just say

class DirtyProperty<T>
Batavia
  • 2,497
  • 14
  • 16
0

Do you understand what the line

where T : class

in your code does?

It is a generic type constraint that says the T should be a class type i.e a reference type.

Remove that line if you want T to be any type.

manojlds
  • 290,304
  • 63
  • 469
  • 417