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.
It’s this line that has you confused:
You expected
bto be copied toaby value, but in fact all that happens is you’ve assigned the reference frombtoa..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:
.Equals()is intended for value equality, and you may need to override .Equals() (and GetHashCode()) for your type to get that right.