...

/

Declaring Local Variables and Access the Default Values of Types

Declaring Local Variables and Access the Default Values of Types

Learn how to declare local variables in C# using types, var, and default values.

We will learn how to declare local variables inside C# method bodies. We will learn to specify the type explicitly, like string or int, and use the var keyword to let the compiler infer the type based on the value assigned. Additionally, we will explore how to get and set the default values of types.

Local variables

Local variables are declared inside methods, and they only exist during the execution of that method. Once the method returns, the memory allocated to any local variables is released. Strictly speaking, value types are released, while reference types must wait for garbage collection.

Specifying the type of a local variable

Let’s explore local variables declared with specific types and using type inference:

  • Type statements to declare and assign values to some local variables using specific types, as shown in the following code:

Press + to interact
int population = 67_000_000; // 67 million in UK
double weight = 1.88; // in kilograms
decimal price = 4.99M; // in pounds sterling
string fruit = "Apples"; // strings use double-quotes
char letter = 'Z'; // chars use single-quotes
bool happy = true; // Booleans have value of true or false

Depending on our code editor and color scheme, it will show green squiggles under each variable name and lighten their text color to warn us that the variable is assigned, but its value is never used. ...