-1

I am a bit confused here. With structs, I cannot directly change its fields as the whole struct is of the value type. But what about classes with value type fields? If I have a public field int X, I can modify it properly. So the only manifestation of value-type nature of its field would be that when passed as an argument, it is a copy?

EDIT: Also

Class A
{
  int B=100;  //this is a field, so reference type. But it is a value type.
}

The address to content of B is stored on the heap, but is the value of B stored on the stack?

John V
  • 4,855
  • 15
  • 39
  • 63

3 Answers3

1

With structs, I cannot directly change its fields as the whole struct is of the value type.

You cannot change fields in situations when C# makes a copy of the struct for you. In other situations, you can modify fields of a struct. Here is a small demonstration of the difference:

struct Foo {
    public int A {get;set;}
    public void SetA(int a) {
        A = a;
    }
}

class Bar {
    Foo f;
    public Foo F {
        get{return f;}
        set {f = value;}
    }
    public void SetFooA(int x) {
        f.SetA(x);
    }
}

public static void Main() {
    Bar b = new Bar();
    b.F.SetA(123);  // b.F makes a copy, so changing A fails
    Console.WriteLine("{0}", b.F.A);
    b.SetFooA(456); // Inside Bar, f.SetA is called directly, so the change works fine
    Console.WriteLine("{0}", b.F.A);
    b.F = new Foo { A = 112233 }; // This also works, because the whole F is assigned
    Console.WriteLine("{0}", b.F.A);
}

If I have a public field int X, I can modify it properly.

The same rule applies to user-defined structs, as long as you modify the whole of it. You can't modify part of an int, because it is not a composite. Modification of a struct works fine when you assign the whole struct at once. In other words, assigning

b.F = new Foo { A = 112233 };

in my example replaces assigning

B = 100;

in your example.

Demo.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

The address to content of B is stored on the heap, but is the value of B stored on the stack?

No. Value type fields of a class are stored on the heap.

Please refer to @Marc Gravell's answer here for more information about this:

Why value-types are stored onto Stacks?

You may also want to read @Eric Lippert's blog post on the subject: https://blogs.msdn.microsoft.com/ericlippert/2010/09/30/the-truth-about-value-types/

In short value types can be stored on the stack but they are not always stored on the stack.

Community
  • 1
  • 1
mm8
  • 163,881
  • 10
  • 57
  • 88
-1

Struct gives you a copy of the original field because a copy of the struct would be passed. Changing it to class would pass a reference to the class and therefore the field would modify if you were to change it.

Nothing
  • 99
  • 12