DEV Community

Cover image for Little drops on C# Interview questions- Value Types x Reference Types
Ynoa Pedro
Ynoa Pedro

Posted on • Updated on

Little drops on C# Interview questions- Value Types x Reference Types

Little drops on C# Interview Questions series
The intention behind this series is to answer with a little bit of context or examples of some of most commons C# interview questions.

Types on .NET

The values on C# are treated in two different types, value types or reference types.

Value types

On value types, the data is stored within its memory allocation on the stack(More on this on the first post of the series). This means that if you assign this to another variable the value is copied and both will work independently.

Some examples of value types are basically primitive types, structures, or enums.

Reference types

On the other hand, reference types held only a pointer to another memory location that holds the data.
Reference types are stored on the Heap which means that the value is available at runtime so when you copy a reference type it only creates another variable which knows the memory address of the actual data allowing it to be targeted by the Garbage collector(more on this later)

Disclaimer

Some Value types can be boxed, or written on top level new C# syntax, this will make value types be stored on Heap. Some more info on this you can find on this amazing video by Nick Chapsas -
https://www.youtube.com/watch?v=jONSIhMST9E&t=185s, also on my next learning post will talk more about boxing and unboxing operations

Some examples of reference types can be arrays, objects, classes.

Wrapping up

Alt Text
Value types are passed by copy and reference types are by? Duh reference. It's like when I copy a value type I'll have two variables holding ice creams and reference types its one ice cream but two variables know where the ice cream is.

Oldest comments (0)