Complete C# Tutorial

Reference Types in C# – Complete Tutorial for Beginners

Reference types in C# store memory addresses instead of actual values. They are used for complex objects and large data.

Let’s break it down super simple!

In C#, reference types don’t store actual values. Instead, they store a memory address (reference) where the real data is kept.

Think of it like saving a contact on your phone—you don’t store the actual person, just their phone number (reference) to reach them!

 

How is it different from value types?

  • Value types (int, double, bool) store actual values directly.
  • Reference types (string, class, array, object) store a memory reference to the actual data.

 

Common Reference Types in C#

  1. string → Stores text
  2. class → Custom objects (like our Person class)
  3. array → Stores multiple values
  4. object → Base type for all C# types

1. String Type Data Type

The string type stores a sequence of characters, like words or sentences.

It can hold letters, numbers, symbols, or spaces and must be written inside double quotes (" ").

✅ Stores text (multiple characters)
✅ Uses string keyword
✅ Always written in double quotes ("Hello", "123", "@C#")
✅ Example values: "John", "C# Programming", "12345"

Strings are useful for names, messages, and user input in programs!

In C#, the string data type is a reference type, even though it behaves like a value type in some cases.

				
					using System;

class Program
{
    static void Main()
    {
        string name = "Alice";
        Console.WriteLine("Hello, " + name + "!");
    }
}
				
			

A string is a sequence of characters, but it’s a reference type even though it behaves like a value type.

				
					using System;

class Program
{
    static void Main()
    {
        string name1 = "Alice";
        string name2 = name1;  // name2 gets a copy, but strings are immutable

        name1 = "Bob";  // Changing name1 does NOT change name2

        Console.WriteLine("Name1: " + name1);
        Console.WriteLine("Name2: " + name2);
    }
}
				
			
Output
				
					Name1: Bob  
Name2: Alice  				
			

Easy Example: A Printed Book

Imagine you write a book and get it printed. Once the book is printed, you cannot change the words inside it. If you need to update anything, you have to print a new version of the book instead of changing the old one.

How It Relates to Programming (Example: Strings in C#)

In C#, a string is immutable, meaning you cannot modify its content directly. Instead, if you try to change it, a new string is created.

				
					string name = "John";  
name = name + " Doe";  				
			
  1. First, "John" is stored in memory.

  2. When " Doe" is added, a new string "John Doe" is created.

  3. The old "John" string is left behind (it will be removed later by the system).

This is why strings are immutable—every change creates a new object instead of modifying the old one!

2. Class Data Type

A class is a blueprint for creating objects just like a house blueprint is used to build multiple houses.

 

Real world example:

1. House Blueprint

Imagine you are an architect designing houses. Before building any house, you first create a blueprint that defines:

  1. Structure: Number of rooms, windows, and doors.
  2. Features: Type of flooring, wall color, and ceiling height.
  3. Functionality: Whether it has a garage, garden, or swimming pool.

Now, this blueprint itself is not a house—it’s just a plan. But using this one blueprint, you can build many houses, each with different details like color, interior design, or furniture.

 
How This Relates to a Class
  • Blueprint (Class) → Defines the structure and properties.
  • Houses (Objects) → Different instances created from the blueprint.
  • Customization (Object Properties) → Each house can have a different color, furniture, or decorations, even though they all follow the same blueprint.
 
2. Class: Car Model
  • Blueprint: A car manufacturer designs a model like a Toyota Corolla.
  • Objects: Different cars built from this model, each with a unique color, owner, or accessories.
 
3. Class: Human
  • Blueprint: Every human has common attributes (eyes, hands, legs) and behaviors (walking, talking, eating).
  • Objects: You, your friends, and your family—all unique instances of the same “human” class.
Programming example
				
					using System;

class House  // Class (Blueprint)
{
    public string Color;
    public int Rooms;
    public int Floors;

    // Method to display house details
    public void ShowDetails()
    {
        Console.WriteLine($"Color: {Color}, Rooms: {Rooms}, Floors: {Floors}");
    }
}

class Program
{
    static void Main()
    {
        // Creating house1 with specific values
        House house1 = new House();
        house1.Color = "Red";
        house1.Rooms = 3;
        house1.Floors = 2;

        // Creating house2 with different values
        House house2 = new House();
        house2.Color = "Blue";
        house2.Rooms = 4;
        house2.Floors = 3;

        // Creating house3 with another set of values
        House house3 = new House();
        house3.Color = "Green";
        house3.Rooms = 5;
        house3.Floors = 1;

        // Displaying details of each house
        Console.WriteLine("House 1 Details:");
        house1.ShowDetails();

        Console.WriteLine("\nHouse 2 Details:");
        house2.ShowDetails();

        Console.WriteLine("\nHouse 3 Details:");
        house3.ShowDetails();
    }
}
				
			
Output
				
					House 1 Details:
Color: Red, Rooms: 3, Floors: 2

House 2 Details:
Color: Blue, Rooms: 4, Floors: 3

House 3 Details:
Color: Green, Rooms: 5, Floors: 1				
			

3. Arrays: A Fun Way to Store Multiple Things!

Imagine you have a box of chocolates 🍫. Instead of holding just one chocolate, this box can store many chocolates in different spots. This is exactly what an array does in programming—it holds multiple values in one place!

How Arrays Work in C#

An array is like a container where you can store multiple items of the same type (like numbers, words, or objects).

 

Key Point

✅ Arrays store multiple values in a single variable.
✅ They don’t hold values directly but store a reference (memory address).
✅ Changing one reference affects all references pointing to the same array.

Example:
A box of markers 🎨 where each slot holds a different colored marker.

				
					string[] markers = { "Red", "Blue", "Green", "Black" };
				
			

Now, markers[0] is “Red”, markers[1] is “Blue”, and so on.

 

Arrays Are Reference Types! What Does That Mean?

Okay, here’s where it gets interesting!

Think of an array like a TV remote 📺:

  • The remote doesn’t store the actual TV—it just points to it.
  • Similarly, an array variable doesn’t store actual values—it stores the address of where the values are in memory.

Example: If you give your friend a copy of your TV remote, they can change the channel, and you’ll see the change too!

 

Proof That Arrays Are Reference Types

Let’s try this in C#:

				
					using System;

class Program
{
    static void Main()
    {
        // Create an array
        int[] numbers1 = { 10, 20, 30 };

        // Assign numbers1 to numbers2 (both now point to the same memory location)
        int[] numbers2 = numbers1;

        // Change a value using numbers2
        numbers2[0] = 99;

        // Print values from both arrays
        Console.WriteLine($"numbers1[0]: {numbers1[0]}"); // 99
        Console.WriteLine($"numbers2[0]: {numbers2[0]}"); // 99
    }
}
				
			
Output
				
					numbers1[0]: 99  
numbers2[0]: 99  				
			

Explanation:

  1. numbers1 is an array {10, 20, 30} stored in memory.
  2. numbers2 = numbers1; → Instead of creating a new array, numbers2 points to the same memory location as numbers1.
  3. Changing numbers2[0] = 99; modifies the same array in memory.
  4. Since both variables refer to the same array, printing numbers1[0] also shows 99.

This confirms that arrays in C# are reference types!

4. Object Data Type – The Ultimate Storage Box!

Alright, let’s make this super simple! Ever had a mystery storage box 🏠📦 where you could put anything inside—toys, books, clothes? Well, in C#, the object data type is just like that! It can store anything—a number, text, even complex things like a car or a house! 🚗🏡

 

So, What Is an object in C#?

  • object is the parent of all data types in C#.
  • It can hold anything—integers, floats, strings, arrays, even your own custom classes.
  • But (big BUT! 😆), it stores data in the heap and works with references instead of direct values.

👜 Real-World Example: A Lost & Found Box!

Imagine a Lost & Found box 📦 at your school, office, or airport. People lose things like keys, wallets, and sunglasses, and instead of keeping them in their pockets, they drop them in the Lost & Found box.

Now, when someone comes looking for their lost item, they don’t get the item directly—instead, they get a claim ticket 🎟️ that points to where their item is inside the box.


 

How Is This Like an object in C#?

✅ The Lost & Found box = Heap memory (where objects are stored)
✅ The claim ticket 🎟️ = Reference (memory address)
✅ The lost items = Actual data (object values)

So, when you take a claim ticket, you’re not holding the actual lost item, but you know where it is. That’s exactly how an object reference works in C#! It doesn’t hold the actual data, just the address of where the data is stored.

That’s exactly how object works! It doesn’t store the actual value but a reference (memory address) to the value.

Proof That object is a Reference Type!

				
					using System;

class Program
{
    static void Main()
    {
        // Create an object and store a value
        object obj1 = 50;

        // Assign obj1 to obj2 (both point to the same memory location)
        object obj2 = obj1;

        // Change obj2's value
        obj2 = 100;

        // Print values
        Console.WriteLine($"obj1: {obj1}"); // 50
        Console.WriteLine($"obj2: {obj2}"); // 100
    }
}
				
			
Output
				
					obj1: 50
obj2: 100				
			

Wait… what? They didn’t change together? 😲
Well, that’s because integers are value types. But if we use a class (which is stored in the heap), the change will reflect. Let’s try!

 
🎭 Example with a Custom Class (Now It’s Clearly Reference Type!)
				
					using System;

class Box
{
    public int Size;
}

class Program
{
    static void Main()
    {
        // Create an object of Box class
        object obj1 = new Box();
        ((Box)obj1).Size = 10; // Casting object to Box

        // Assign obj1 to obj2 (both point to the same memory)
        object obj2 = obj1;

        // Change obj2's value
        ((Box)obj2).Size = 20;

        // Print values
        Console.WriteLine($"obj1 size: {((Box)obj1).Size}"); // 20
        Console.WriteLine($"obj2 size: {((Box)obj2).Size}"); // 20
    }
}
				
			
Output
				
					obj1 size: 20
obj2 size: 20				
			

Boom! 💥 Now you see it! Changing obj2.Size also changed obj1.Size because both variables were pointing to the same object in memory!

 

Key points

object is a reference type, meaning it stores a reference (memory address) instead of direct values.
✅ It can hold any data type, making it super flexible! 🎉
✅ If an object stores a value type, it creates a copy (like in the first example).
✅ If it stores a reference type (like a class), all variables point to the same memory location.

 

Final Thought!

Think of an object like Google Drive! ☁️ You don’t store the actual files on your laptop—you just access the reference (link) to them! And when you update a file, everyone sees the change instantly!

Conclusion

Now, you totally get reference type data types like string, class, array, and object! They don’t hold actual values, just memory addresses (references). So, when you change one, boom 💥—it affects all references pointing to it!

Remember, strings are special (immutable!), arrays are shared (be careful!), classes are blueprints, and objects? Well, they’re the ultimate storage box! 📦

But hey, we’re not done yet! There are more cool reference types waiting for you—like Delegate, Interface, and Dynamic! You’ll learn about them soon, and trust me, they’re just as exciting! 😃

So, keep going, keep exploring, and happy coding! 💻

Leave a Comment

Share this Doc

Reference Type

Or copy link