Class Definition

suggest change

Classes inherit from System.Object, are reference types, and live on the heap. A reference-type argument is passed by value: the method gets a copy of the reference.

public class MyClass
{
    public int a;
    public int b;
}

The method receives a copy of the reference to the same object. Changes to that object's fields are visible to the caller. Assigning a new object to the parameter is not, unless the parameter is ref or out.

MyClass instanceOfMyClass = new MyClass();
instanceOfMyClass.a = 5;
instanceOfMyClass.b = 6;

AddNumbers(instanceOfMyClass);

public void AddNumbers(MyClass sample)
{
    int z = sample.a + sample.b; // z becomes 11
    sample.a = sample.a + 5; // now we changed a to be 10
    z = sample.a + sample.b; // now z becomes 16
}

When sample.a is set to 10, instanceOfMyClass.a changes too, because both variables refer to the same object. The parameter is not a copy of the object.

Reference types live on the heap. The reference itself is passed by value.

Feedback about page:

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



Table Of Contents