CHASH Tutorial



C# REFERANCE TYPES


Reference Types in C#

In C#, data types are divided into two categories: Value Types and Reference Types. Reference types store references (or addresses) to the actual data, rather than the data itself.

What Are Reference Types?

When you create a reference type variable, it holds the address of the data in memory, not the actual value. Multiple variables can reference the same object in memory.

Common Reference Types

  • Classes (e.g., class Person { })
  • Arrays (e.g., int[] numbers;)
  • Strings (although they behave a bit like value types)
  • Delegates and Interfaces

How Reference Types Work

When you assign one reference type variable to another, both variables point to the same object. Changes made via one variable affect the other.

class Person
{
    public string Name;
}

Person person1 = new Person();
person1.Name = "Alice";

Person person2 = person1;  // Both refer to the same object
person2.Name = "Bob";

Console.WriteLine(person1.Name);  // Outputs: Bob
  

Key Points

  • Reference types store the address of the data, not the data itself.
  • Multiple variables can refer to the same object.
  • Modifying the object via one variable affects all variables referencing it.
  • Reference types are stored on the heap memory, while value types are stored on the stack.
  • Strings are reference types but are immutable, meaning their values cannot be changed after creation.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review