Language: EN

csharp-que-son-variables

What are and how to use variables in C#

A variable is a storage space in memory with a symbolic name (identifier) that can hold a value of a specific type.

Variables allow you to store temporary data that can be used later in the code.

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;

For example, to declare an integer variable named age:

int age;

Default Values

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

Value Types

For value types, the default values are:

  • int: 0
  • float: 0.0f
  • double: 0.0d
  • char: '\0' (null Unicode character)
  • bool: false

Reference Types

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

string cadena; // cadena is null by default
int[] array; // array is null by default
object miObjecto; // object is null by default.

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 does not contain anything.

Before using a Reference Type variable, you have to assign it an instance, or you will have a runtime error

Value Assignment

Assigning a value to a variable is giving it an initial value or modifying its existing value. The syntax for assigning a value to a variable is:

variableName = value;

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

age = 25;

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

int age = 25;

Practical Examples

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

Student data management

In this example, we show how to manage basic student data, such as their name and age. This example illustrates how to declare and assign values to variables of different data types.

// Declare variables
public string name;  // for the student's name
public int age;       // for the student's age

// Assign values to the variables
name = "Ana"; 
age = 21;

// Print the student's data to the console
Console.WriteLine($"{name} is {age} years old");

Calculation of the area of a circle

In this example, we calculate the area of a circle using a basic mathematical formula. A constant is declared for the value of PI and a variable for the radius of the circle.

// Declare a constant for the value of PI
const double PI = 3.14159;

// Declare a variable for the radius of the circle
double radius = 5.0;

// Calculate the area of the circle using the formula: area = PI * radius^2
double area = PI * radius * radius;

// Print the result to the console
Console.WriteLine($"The area of the circle is: {area}");