0

Suppose I have a class MyClass. Then I have an instance of this class like:

MyClass myobject = ...  

Then I want to do 2 things:

  1. Copy the instance to another object.
  2. Compare two instances to check if they are the same (equal).

What's the simplest solution for this? I have searched the internet and found many solutions, but none of them are as simple as I expected.

Ani
  • 111,048
  • 26
  • 262
  • 307
KentZhou
  • 24,805
  • 41
  • 134
  • 200
  • http://stackoverflow.com/questions/78536/cloning-objects-in-c-sharp http://stackoverflow.com/questions/1031023/copy-a-class-c-sharp http://msdn.microsoft.com/en-us/library/ms173116.aspx Google is your friend! – Mark Kram Nov 08 '11 at 14:18
  • 2
    what do you expect exactly? Why is implementing clonable not ok for you? what other alternatives have you found and find too complicated? – Davide Piras Nov 08 '11 at 14:18

3 Answers3

1

Implement IEquatable(t) in your class. You can implement your own comparison logic in the Equals() method.

You might also want to check out ICloneable.

Simon
  • 6,062
  • 13
  • 60
  • 97
  • 1
    `ICloneable` is not a very good interface for several reasons. The article you linked to even suggests that you shouldn't use it. – svick Nov 08 '11 at 14:24
  • That's why I said 'might' and pointed the OP towards that link rather than MSDN :) The whole point of the interface is that the implementation is up to you. The OP can decide how to implement the clone and what he needs to document about his implementation. – Simon Nov 08 '11 at 14:40
0

Copy the instance to another object.

I assume not just coping the object reference but coping the content. For this purpose you have to implement IClonable interface in your MyClass class.

Compare two instances to check if they are the same (equal).

You have to implement IEquatable interface in your Myclass class.

Upul Bandara
  • 5,973
  • 4
  • 37
  • 60
  • 1
    In both cases, that's one way to do it, not the only one. You don't “have to” do that. – svick Nov 08 '11 at 14:25
0

As others have pointed out for equality comparison, implement IEquatable or just override the Equals() and GetHashCode() methods.

Cloning (copying) is not a trivial problem in memory-managed languages like C#, since you can't just copy memory. Implementing IClonable is one possibility, but there will be confusion from the client perspective of whether you are performing deep vs. shallow cloning.

In my experience, one of the simplest ways to implement cloning is to make a class serializable, and simply serialize and deserialize it. And, of course, you will reap other benefits to having a Serializable object as well.

afeygin
  • 1,213
  • 11
  • 26