Struct Definition

suggest change

Structs inherit from System.ValueType and are value types. A local may be stored on the stack. A field is stored inside the object that contains it. Parameters 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;

AddNumbers(a,b);

public void 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.

Value types are passed by value. A local may be stored on the stack. A field is stored inside the object that contains it.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents