Object equality in .NET

c#, equality, object

Solution

It's this line that has you confused:

a = b;

You expected `b` to be copied to `a` by value, but in fact all that happens is you've assigned the reference from `b` to `a`.

.Net divides the world into two categories: reference types and value types (there's also delegate types and a couple others, but that's another story). Any class you define is a reference type, and there are a few important things to remember about reference types:

- There's no built-in way to do a deep copy

- Be careful checking equality. == is intended for reference equality (do the variables refer to the same object) while `.Equals()` is intended for value equality, and you may need to override .Equals() (and GetHashCode()) for your type to get that right.

- assignment just copies the reference (this is the part that bit you)

Problem

I feel pretty ignorant asking this, but would someone be able to explain to me why this is happening? ``` class MyClass{ public int i {get; set; } } class Program { static void Main(string[] args) { MyClass a = new MyClass(); MyClass b = new MyClass(); b.i = 2; a = b; a.i = 1; Console.Write(b.i + "\n"); //Outputs 1 } } ``` This makes sense to me were I using pointers and all that great stuff, but I was under the impression that with C# that "b" would remain independent from "a." Am I just using some terribly bad practice? Maybe someone could point me towards something that explains why this is so in C#? Thanks.

Original source