Basic Operations and Syntax

Your Progress in this Chapter

0%

0 / 12 units completed

Chapter Overview

Variables

Section 1.2 of 613 min6 code examples

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#

1
2
3
4
Code is ready to run

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#

1
2
3
4
Code is ready to run
CategoryMemoryTypical TypesCopy Behavior
Value TypesStackint, double, bool, structCopies the actual value
Reference TypesHeapstring, class, Array, objectCopies 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#

1
2
3
Code is ready to run
OutputFrom the book
Precision: 0.0001, Tolerance: 1E-06

.. Admonition:: Example 2 : Constant Variables

Example 4C#

1
2
3
4
Code is ready to run
OutputFrom the book
Acceleration due to gravity: 9.81 m/s²

.. Admonition:: Example 3 : Scope and Braces

Example 5C#

1
2
3
4
5
6
7
Code is ready to run
OutputFrom the book
Sum: 30

.. Admonition:: Example 4 : Nullable Reference Types

Example 6C#

1
2
3
4
Code is ready to run
OutputFrom the book
Project: Sepal Solver