Variables in C#
A variable is a symbolic name given to a memory location. In C#, variables are categorized into two main types based on how they store data in memory: Value Types and Reference Types.
1. Value Types
Value types store the actual data directly in the location where the variable is declared (usually on the stack). When you copy a value type, a complete independent copy of the data is made.
Example 1C#
2. Reference Types
Reference types do not store the actual data. Instead, they store a reference (a pointer) to the memory address where the data is kept (usually on the heap). When you copy a reference type, you are only copying the pointer, not the data itself.
Example 2C#
| Category | Memory | Typical Types | Copy Behavior |
|---|---|---|---|
| Value Types | Stack | int, double, bool, struct | Copies the actual value |
| Reference Types | Heap | string, class, Array, object | Copies the reference (pointer) |
Variable Declaration and Initialization
C# is a strongly-typed language. You must declare the type of a variable before you use it. You can also use the var keyword for implicit typing, where the compiler determines the type based on the value assigned.
Examples
.. Admonition:: Example 1 : Explicit vs Implicit Typing
Example 3C#
Precision: 0.0001, Tolerance: 1E-06
.. Admonition:: Example 2 : Constant Variables
Example 4C#
Acceleration due to gravity: 9.81 m/s²
.. Admonition:: Example 3 : Scope and Braces
Example 5C#
Sum: 30
.. Admonition:: Example 4 : Nullable Reference Types
Example 6C#
Project: Sepal Solver