2

Let's say i have a class like that:

class Test
{
   string asd;
   int dsa;
}

Later, I create instance of this class, then later it may change values for data members.
I need a simple compare method without comparing all class members.
Something like that:

Test t = new Test();
t.asd = "asd";

SOMETHING SMTH = GetSOMETHINGof(t);

a.dsa = 3;

if (GetSOMETHINGof(t) != SMTH)
   //object modified

Maybe someone know built-in things that can be used for that? I know i can implement Equal and etc, but that's not what i want. There is too much classes and a lot of members.
I use C# and .net 4.0

Kosmo零
  • 4,001
  • 9
  • 45
  • 88
  • could you use private variables, public properties and implement the propertychanged event on those properties? that way you can subscribe to the event and have it fire when something changes – wterbeek Sep 14 '12 at 06:10
  • Maybe this can help you : http://stackoverflow.com/questions/2363801/what-would-be-the-best-way-to-implement-change-tracking-on-an-object – David Sep 14 '12 at 06:10
  • there is a lot of changes in source code if switch to properties. I can't pass properties as ref, out and etc. I need something more cool :D – Kosmo零 Sep 14 '12 at 06:15
  • or this http://stackoverflow.com/questions/9624318/how-to-implement-a-simple-generic-comparison-in-c-sharp – ravi Sep 14 '12 at 06:17
  • This will be helpful http://stackoverflow.com/questions/2502395/comparing-object-properties-using-reflection – Prasanna Sep 14 '12 at 06:18
  • i found an interesting way here: http://stackoverflow.com/questions/2502395/comparing-object-properties-using-reflection by Oskar Kjellin. I just hope base types as int and etc don't have properties :D since i going o modify it for recursive object properties comparing. Thanks to everyone! – Kosmo零 Sep 14 '12 at 06:32
  • err, also hope it works for private and protected members too... but would be weird if i can that easy access private member just by calling GetProperties() – Kosmo零 Sep 14 '12 at 06:45

2 Answers2

1

Compare .NET Objects 1.4.2.0 by Greg Finzer http://www.nuget.org/packages/CompareNETObjects

Community
  • 1
  • 1
Prasanna
  • 4,583
  • 2
  • 22
  • 29
1

Add extra property to keep state of the object:

public class A
{
    public bool HasChanged { get; set; }

    object _Value;
    public object Value
    {
        get
        {
            return _Value;
        }
        set
        {
            HasChanged = value != _Value;
            _Value = value;
        }
    }

    public A(object _value)
    {
        _Value = _value;
        HasChanged = false;
    }
}

and use it:

        A a = new A(5);
        Console.WriteLine(a.HasChanged);  //false
        a.Value = 6;
        Console.WriteLine(a.HasChanged);  //true
        a.HasChanged = false;
        Console.WriteLine(a.HasChanged);  //false
horgh
  • 17,918
  • 22
  • 68
  • 123