Understanding Data Types In C#

Data types in C# are separated into Value types and Reference types, Understand the concept behind each of them is definitely essential for beginners.

1. Value Type

Structs and Enumeration falls under the Value type category. Structs are the numeric types(int, char, byte, float, double), bool and even user defined structs.

So, “What’s actually a value type variable?”. Well, they are variables that store the actual data, rather than a reference to it.

They are passed by value; meaning if you assigned a variable to another one, it gets assigned to a new, independent copy of the variable’s value, and any change in either variable will affect only the changed variable. Also it’s worth to mention that Value types are allocated on the stack.

int foo = 3;
int bar = foo;
bar = 10;
Console.WriteLine(foo); // 3
Console.WriteLine(bar); // 10

2. Reference Type

Class, interface, string, object, All of them fall under Reference type category. So, the question again “What’s actually a reference type variable?”. Not surprisingly, Those are the Variables that store references to the actual data rather than the data itself. Reference types are allocated on the heap.

Now, if you are following along from the previous section, you might be asking these questions:

“Are they passed by reference or value?”. Assigning a Reference type variable to another variable actually copies the reference to the object but not the object itself. It means, since the reference type variable holds the reference to the actual data, so it passes this reference and not the actual data. So, it’s pass by value!

“What if i assigned a reference type variable to anther, and then i changed any of them?”. Since they are referencing the same memory location, so any changes in any of the variables will affect the same memory location, and hence, both reference type variables will get affected by this change.

class Program
{
static void Main(string[] args)
{
Student stu1 = new Student(5,"Jason");
Student stu2 = stu1;
            stu2.idNum = 10;
stu2.myName = "Smith";
            Console.WriteLine(stu1.idNum); // 10 
Console.WriteLine(stu1.myName); // Smith
}
}
public class Student
{
public int idNum { get; set; }
public string myName { get; set; }

public Student(int id, string name)
{
idNum = id;
myName = name;
}
}

To grasp the previous idea, and have a better understanding of what’s actually happen in the memory allocation. First, I assigned stu1 to stu2, So, now both reference the same memory location.

Understanding Data types in C# — Reference Types

And then when i changed the properties idNum and myName, stu1 changed too.

Understanding Data types in C# — Reference Types
Show your support

Clapping shows how much you appreciated Omar El Gabry’s story.