csharp-que-son-variables

What are and how to use variables in C#

  • 3 min

An variable is a reserved space in memory with a symbolic name (identifier), in which we can store a value of a specific type.

Variables allow us to store temporary data that we can use later throughout our program.

If you want to learn more, check out the Introduction to Programming Course

Variable Declaration

Declaring a variable in C# involves specifying its type and giving it a name. The basic syntax for declaring a variable is:

type variableName;
Copied!

For example, to declare an integer variable named age:

int age;
Copied!

Default Values

In C#, uninitialized variables are assigned default values (depending on their type).

Value Types

For value types, the default values are:

TypeDefault Value
int0
float0.0f
double0.0d
char'\0' (Unicode null character)
boolfalse

Reference Types

For reference types, the default value is always null, which indicates that the variable does not reference any location in memory.

string str; // str is null by default
int[] array; // array is null by default
object myObject; // object is null by default.
Copied!

This leads to one of the most common errors in programming. If you access a Reference Type variable before creating it, you will get a null exception error because your variable contains nothing.

Before using a Reference Type variable, you must assign an instance to it, or you will have a runtime error (i.e., when the program is running)

Value Assignment

Assigning a value to a variable means giving it an initial value or modifying the value it contains. The syntax for assigning a value to a variable is:

variableName = value;
Copied!

For example, to assign the value 25 to the variable age:

age = 25;
Copied!

It is also possible to declare and assign a variable in a single line:

int age = 25;
Copied!

Practical Examples

Let’s look at some very simple examples of using variables in C#. These examples show how to declare and use variables to perform calculations and manage data.