C# Variables

A variable in C# is a storage location in the computer’s memory that is used to hold data. Each variable has:

  1. A name to identify it (like a label on the storage).
  2. A data type to specify the kind of data it can hold (like numbers, text, etc.).
  3. A value which is the data the variable holds (like 10, “Hello”, true, etc.).

Syntax:


dataType variable_name = variable_value;

Example:


string a = "Hello World";

Rules for declare Naming Variables

1. It must start with a letter (a-z, A-Z) or an underscore (_).

2. Subsequent characters can include letters, digits (0-9), or underscores.

3. It can not start with a digit.

4. It can not be a C# keyword (e.g., int, class, bool).

5. Variable names are case-sensitive.

Example of Valid Variable

int age;
string name;
bool isAdmin;

Example of Invalid Variable

string 1age;
string class;

Declaring and Initializing Variables

1. Declaration: Telling the program about the variable’s type and name.

2. Initialization: Giving the variable a value

1. You can declare and initialize a variable in a single step:

Example:


int age = 35;

2. declare and initialize separately


int age;         // Declaration
age = 35;        // Initialization

Default Values of Variables

If you declare a variable without giving it a value, C# assigns a default value depending on the type.

  • int gets 0
  • bool gets false.
  • string gets null (because it’s an object type).
  • double gets 0.0.

C# Variables – Interview Questions

Q 1: What is a variable?
Ans: A variable is used to store data in a program.
Q 2: How do you declare a variable in C#?
Ans: int x = 10;
Q 3: Can variable names start with numbers?
Ans: No, variable names cannot start with numbers.
Q 4: What keyword is used for implicit typing?
Ans: var
Q 5: Are variables type-safe in C#?
Ans: Yes, C# is strongly type-safe.

C# Variables – Objective Questions (MCQs)

Q1. Which keyword is used to declare a variable in C#?






Q2. Which of the following is a valid variable declaration in C#?






Q3. What is the default value of an uninitialized integer variable in C# (inside a class)?






Q4. Which of the following variable names is invalid in C#?






Q5. What is the scope of a variable declared inside a method in C#?






Related C# Variables Topics