Struct Definition

Download .net eBook


Structs inherit from System.ValueType, are value types, and live on the stack. When value types are passed as a parameter, they are passed by value.

Struct MyStruct
    public int x;
    public int y;

Passed by value means that the value of the parameter is copied for the method, and any changes made to the parameter in the method are not reflected outside of the method. For instance, consider the following code, which calls a method named AddNumbers, passing in the variables a and b, which are of type int, which is a Value type.

int a = 5;
int b = 6;


public AddNumbers(int x, int y)
    int z = x + y; // z becomes 11
    x = x + 5; // now we changed x to be 10
    z = x + y; // now z becomes 16

Even though we added 5 to x inside the method, the value of a remains unchanged, because it's a Value type, and that means x was a copy of a's value, but not actually a.

Remember, Value types live on the stack, and are passed by value.


Contributors: 2
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial:

Download eBook