Declare a Variable in C#

To declare a variable in C#, you write the type, followed by the name, followed by = and the initial value:

string choice = "1";
  • string — the type of value the variable will hold
  • choice — the name you use to refer to this variable
  • "1" — the initial value assigned to it

Type Inference with var#

Instead of writing the type explicitly, you can use var and let the compiler figure it out:

var choice = "1";

The type is inferred from the value on the right. This works as long as you assign a value when declaring the variable.

Common Types#

TypeHoldsExample
stringText"Hello"
intWhole numbers42
doubleDecimal numbers3.14
boolTrue or falsetrue

Naming Rules#

  • Names can contain letters, digits, and underscores.
  • Names cannot start with a digit.
  • Names are case-sensitive: choice and Choice are different variables.
  • Use clear, descriptive names that reflect the value being stored.

Resources#