Sunday, June 23, 2024 21:53

Table of contents >> Introduction > Value and reference types

Value and reference types

Variables in C# can be categorized in two main types: value and reference types. What is the difference between them?

Value types are stored in a special area which is called the execution stack and their value is directly stored and accessed. Here is the complete list of value types: sbyte, byte, short, ushort, int, long, ulong, float, double, decimal, char, bool. As a specific characteristic for them, the memory allocated for them by the program is freed when their execution scope finishes. For instance, when we have a block of code, like the Main function, when it finishes executing, all the value type variables stored in the stack are disposed.

Reference types do not hold direct values. They actually store an address (reference) in the program’s execution stack, and it is that reference that points to the actual value stored in the dynamic memory (called heap). Here is an example of how a reference variable is represented: 0x009F54A9. Unlike value types, reference types can hold null values, and they can only point to objects of the same type.

Another distinct feature of reference types is that they allocate dynamic memory for their declaration. They are automatically managed by something called garbage collector, which automatically frees their memory when they are no longer used. Because of that, reference types are a bit slower than the value types. Because reference types are allocated and released dynamically and automatic, their size might not be known in advance. For instance, when we declare a variable of type string, which can hold text, it will not know in advance the length of the text we will store inside it.

You can much more easily imagine value and reference types using real world examples. If we want to create an object, and only one object, we are creating a value type. For instance, we create a sculpture, and that is it. We place it on a stand, and that is it. So, value types are easy to be understood. We design and create an object, and any modification we are making is performed directly on that single object.

On the other side, let’s say we are a engineer, and we are hired to build 300 planes. Do we design every single one of the planes? NO! We design a blueprint, of which we are creating copies (called references in C#). So, when using reference types, we are not performing actions or using the original object directly (the blueprint). Instead, every time we need, we create an instance (copy) of it, and that copy is what we are modifying and using.

The concepts explained in this lesson are also shown visually as part of the following video:

Tags: , ,

Leave a Reply

Follow the white rabbit