-
September 28th, 2010, 03:14 AM
#1
Automatic definition of Equals etc?
Hi,
I'm in the process of learning C#. Coming from C++, I'm used to getting some methods for free from the compiler, most notably an equality operator (that tests equality of all fields) and a copy constructor.
In C#, it seems I have to write these methods myself, except if I use structs instead of classes, where equality and copying are automatically defined. However, since everyone seems to recommend against using structs in most cases, I wonder if it is possible to get anything similar with classes. That is, can I in any way instruct the compiler to make a default Equals method and copy constructor for my class?
Henrik
-
September 28th, 2010, 08:56 AM
#2
Re: Automatic definition of Equals etc?
The reason it "just happens" with strutcs is because they are value-based. When you set one struct equal to another, the values are copied over. With classes it's a bit different. They are reference based. So when you set one equal to another, the pointer gets copied over... now both variables point to the same memory location, and thusly the same data.
When it comes to copying... there's two types: shallow and deep... shallow will copy references, while a deep copy will copy values themselves. Since the compiler has no way of knowing which version you could possibly want, it leaves the copy implementation up to you. Not to mention what to do when your object contains objects too... do you shallow or deep copy those? and so on...
-tg
-
September 28th, 2010, 03:18 PM
#3
Re: Automatic definition of Equals etc?
Originally Posted by TechGnome
The reason it "just happens" with strutcs is because they are value-based. When you set one struct equal to another, the values are copied over. With classes it's a bit different. They are reference based. So when you set one equal to another, the pointer gets copied over... now both variables point to the same memory location, and thusly the same data.
When it comes to copying... there's two types: shallow and deep... shallow will copy references, while a deep copy will copy values themselves. Since the compiler has no way of knowing which version you could possibly want, it leaves the copy implementation up to you. Not to mention what to do when your object contains objects too... do you shallow or deep copy those? and so on...
-tg
Great explanation. Thank you, TechGnome.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|