Skip to content

Variables

In C#, a variable is a named storage location that can hold data, and its value can be changed during the program's execution. Variables are essential for storing and manipulating data in a program. C# is a statically-typed language, which means that the type of a variable must be declared at compile-time.

Declaration

Before using a variable, you need to declare it by specifying its data type and giving it a name. The syntax is as follows:

C#
data_type variable_name;

For example:

C#
int age;

Initialization

You can also assign an initial value to a variable during declaration. This process is known as initialization:

C#
data_type variable_name = initial_value;

For example:

C#
int age = 25;

Variables in a Program

Here is an example of using variables in a program:

C#
using System;

class Program
{
    static void Main()
    {
        // Declaration without initialization
        int myNumber;

        // Initialization during declaration
        double pi = 3.14;

        // Declaration and initialization in separate steps
        char grade;
        grade = 'A';

        // Displaying values
        Console.WriteLine("My number: " + myNumber); // Compiler error: use of unassigned local variable
        Console.WriteLine("PI: " + pi);
        Console.WriteLine("Grade: " + grade);
    }
}

Note

In the example above, attempting to use the myNumber variable without initializing it first will result in a compilation error. This is because C# does not allow the use of uninitialized variables.

Variable Types

C# supports various data types, including but not limited to:

  • int: Integer (whole numbers)
  • double: Double-precision floating-point
  • char: Character
  • string: String of characters
  • bool: Boolean (true or false)
  • ...and more.

Example:

C#
int count = 10;
double temperature = 98.6;
char initial = 'C';
string greeting = "Hello, World!";
bool isCorrect = true;

Warning

Variable names in C# are case-sensitive, and you should choose meaningful names to improve code readability.

Further Reading