C# ยท Chapter 7 of 46

C# Variables

A variable is a named location in memory used to store a value. In C#, every variable must be declared with a specific type before it can be used.

Variable names must start with a letter or underscore, can contain digits, and cannot be a reserved keyword. Choosing clear variable names makes your code much easier to read.

Syntax
type name = value;

Declaring and initializing

A declaration reserves memory of the right type, such as `int age;`. You can also initialize a variable with a value at the same time, like `int age = 25;`.

Naming rules

Names are case-sensitive and can include letters, digits and underscores, but cannot start with a digit. Avoid C# keywords like int, class or for as variable names.

Example 1 (csharp)
using System;

class Program {
  static void Main() {
    int age = 25;
    double price = 9.99;
    Console.WriteLine(age + " " + price);
  }
}
Output
25 9.99

Two variables of different types are declared, initialized and printed.

Example 2 (csharp)
using System;

class Program {
  static void Main() {
    int x, y;
    x = 5;
    y = 10;
    Console.WriteLine("Sum: " + (x + y));
  }
}
Output
Sum: 15

Multiple variables of the same type can be declared on one line, then assigned separately.

Key points

  • Every variable in C# has a fixed, declared type.
  • Variables can be declared and initialized in one statement.
  • Names are case-sensitive and cannot start with a digit.
  • The `var` keyword lets the compiler infer the type from the value.
๐Ÿ’ก Note: Local variables must be initialized before use, or the compiler will give an error.

๐Ÿ“ Quick Quiz

1. What must you specify when declaring a variable in C#?

2. Which is a valid C# variable name?

3. What keyword lets the compiler infer a variable's type?