Lesson 6 +10 XP

C# Variables

C# Variables

A variable is a container that stores a value. In C# you tell the compiler the type of data the variable will hold.

Declaring a variable

type variableName = value;
int myNum = 5;
double myDouble = 5.99;
char myLetter = 'D';
bool myBool = true;
string myText = "Hello";

Declaring without assigning

You can declare first and assign later:

int myNum;
myNum = 15;

The var keyword

C# can infer the type for you with var:

var myNum = 5;          // int
var myText = "Hello";   // string

The compiler figures out the type from the value.

Naming rules (identifiers)

  • Names can contain letters, digits, and the underscore _.
  • They must start with a letter or underscore, not a digit.
  • Names are case-sensitive (myVar vs myvar).
  • They cannot be reserved keywords (like int, class, void).
  • C# convention: variables use camelCase (myAge).

Display variables

string name = "John";
Console.WriteLine(name);

Combine text and variables

string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
Console.WriteLine(fullName);   // John Doe
int x = 5;
int y = 6;
Console.WriteLine(x + y);      // 11

Multiple variables

int x = 5, y = 6, z = 50;
Console.WriteLine(x + y + z);

TL;DR

  • Declare with type name = value;.
  • var lets C# infer the type.
  • Identifiers: letters, digits, underscores; start with letter or underscore.
  • Use camelCase for variables by convention.