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:
Get hands-on with 1400+ tech skills courses.