.NET Framework Custom Types Class Definition

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Classes inherit from System.Object, are reference types, and live on the heap. When reference types are passed as a parameter, they are passed by reference.

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

Passed by reference means that a reference to the parameter is passed to the method, and any changes to the parameter will be reflected outside of the method when it returns, because the reference is to the exact same object in memory. Let's use the same example as before, but we'll "wrap" the ints in a class first.

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

AddNumbers(instanceOfMyClass);

public 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
} 

This time, when we changed sample.a to 10, the value of instanceOfMyClass.a also changes, because it was passed by reference. Passed by reference means that a reference (also sometimes called a pointer) to the object was passed into the method, instead of a copy of the object itself.

Remember, Reference types live on the heap, and are passed by reference.



Got any .NET Framework Question?