C# - Reference Type parameters

In C#, reference type parameters refer to parameters that are passed to methods not by their value, but by a reference to their actual memory location. This means that if you modify the parameter inside the method, the change will be reflected on the original object outside the method. This concept is used with reference types such as classes, interfaces, delegates, and arrays.

Here is an example that demonstrates this concept:


using System;

public class Book
{
    public string Title { get; set; }
}

public class Program
{
    public static void ChangeBookTitle(Book book)
    {
        book.Title = "C# in Depth"; // This change affects the original 'Book' instance
    }

    static void Main()
    {
        Book myBook = new Book();
        myBook.Title = "Initial Title";

        Console.WriteLine("Original Title: " + myBook.Title); // Outputs "Initial Title"

        ChangeBookTitle(myBook); // Passes the 'Book' instance by reference

        Console.WriteLine("Updated Title: " + myBook.Title); // Outputs "C# in Depth"
    }
}

If you run the above code, you will get the following output:


Original Title: Initial Title
Updated Title: C# in Depth

This code snippet demonstrates the behavior of reference type parameters in C#:

  • We created an instance of the Book class called myBook and set its Title property to "Initial Title".
  • Then, we printed out the original title.
  • We called the ChangeBookTitle method and passed myBook as an argument. Since Book is a reference type, the method modified the Title of the original Book instance.
  • Finally, printing the title after the method call reflects the change made inside the method, showing "C# in Depth".

Thus, any changes made to reference type parameters inside a method affect the original objects.