VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/c-sharp-variables/

⇱ Variables in C# - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Variables in C#

Last Updated : 20 Apr, 2026

A variable in C# is a named memory location used to store data during program execution. The stored value can be accessed, modified, and reused throughout the program.

Each variable consists of three components:

  • Name: Identifier used to reference the variable.
  • Type: Specifies the type of data the variable can store (e.g., int, char, double).
  • Value: The actual data stored in the variable.

Output
3
7

Rules for Naming Variables

  • Variable names can contain the letters ā€˜a-z’ or ’A-Z’ or digits 0-9 as well as the character ā€˜_’.
  • Variable names cannot start with a digit.
  • The name of the variable cannot be any C# keyword say int, float, null, string, etc.

Variable Declaration

Declaration means defining the data type and name of a variable. At this stage, the variable is created but no value is assigned.

dataType variableName;

Example:

int x;
double price;
char grade;

Here:

  • int, double, and char are data types.
  • x, price, and grade are variable names.

Variable Initialization

Initialization means assigning a value to a variable after it has been declared. Example:

int x;
x = 5;

In this example, the variable x is declared first and later assigned the value 5.

A variable can also be declared and initialized in a single statement.

int y = 7;

  • y is declared as an integer.
  • The value 7 is assigned at the same time.

There are two basic ways for initialization as mentioned below:

1. Compile Time Initialization

In compile-time initialization, the value of the variable is assigned when the program is written. The value remains fixed during execution. Example:


Output
Value of x is 32
Value of y is 0

Here, the values of x and y are known before the program runs.

2. Run Time Initialization

In run-time initialization, the value of the variable is assigned during program execution. The value may come from user input, function calls, or program logic. Example:

Input:

Enter a number: 45

Output:

Value of num is 45

Explanation: Console.ReadLine() reads input from the user and the entered value is stored in the variable num.

Comment
Article Tags:

Explore