0

something is not very clear to me while using c#, hope I can get some answers here

using System;

public struct SampleStruct {
    public float v;
}
public class SampleClass {
    public float v;
}
public class Program
{
    private float aaa;
    private float bbb;
    private SampleClass c111 = new SampleClass();
    private SampleClass c222 = new SampleClass();
    private SampleStruct AAA = new SampleStruct();
    private SampleStruct BBB = new SampleStruct();

    public void Main()
    {

      //test int field
      aaa = 10;
      bbb = aaa;
      bbb = 9;
      Console.WriteLine("int test: " + aaa);

      //test class
      c111 = new SampleClass { v = 10 };
      c222 = c111;
      c222.v = 9;
      Console.WriteLine("class test: " + c111.v);

      //test struct
      AAA = new SampleStruct { v = 10 };
      BBB = AAA;
      BBB.v = 9;
      Console.WriteLine("class struct: " + AAA.v);
    }
}


//output
//int test: 10
//class test: 9
//class struct: 10

My question is why a Class object behaviors differently than a struct here as you can see if I change the latter object it affects to the object where it copied from

Joe Lu
  • 2,240
  • 1
  • 15
  • 18
  • 4
    Look up value types vs reference types. – ProgrammingLlama Dec 27 '20 at 13:27
  • hint: an `int` is a `struct` (also known as "value type"). ([see documentation](https://learn.microsoft.com/en-us/dotnet/api/system.int32?view=net-5.0)). and follow John's advice ;) – Pac0 Dec 27 '20 at 13:31
  • When you assign a struct (value) object to a variable, a copy of the struct is made, so that both objects are separate. When you assign a class (reference) object to a variable, just the reference to the object is copied, so there is only one object with two references pointing to it. – Matthew Watson Dec 27 '20 at 13:31

1 Answers1

1

For this you need to understand that struct is a value type while class is a reference type which means that in struct the data is copied by value which means every time a new copy of data is created while in case of reference type we just have a new copy of reference pointing to same data.

When this line executes:

c222 = c111;

both c222 and c111 are pointing to same data or memory location. Now when the following line executes :

c222.v = 9;

both c222 and c111 are able to see the changed data as both are pointing to same data or memory location.

while when this line executes:

BBB = AAA;

there is new copy of the data that is in the AAA but changing BBB will not affect AAA as BBB is copied by value from AAA not reference.

You should go through the following to get more understanding of this:

Value Types and Reference Types Microsoft Docs

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160