Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 182 ยท Variables and Types

Variables and var

Learn C# variables - declaring and assigning, definite assignment, var type inference, default values, scope rules, naming conventions and discards.

A variable is a named place in memory that holds a value your program can read and change. Almost every line of real code uses them: a player's score, the text a user typed, the total of an invoice. C# is a statically typed language, which means every variable has a type that is fixed when you write the code and checked by the compiler. You cannot put text in a variable meant for numbers and discover the mistake only when the program crashes.

This lesson shows how to declare and assign variables, why the compiler sometimes refuses to let you read one (definite assignment), how var lets the compiler infer the type, what default values are, how scope limits where a name is visible and how to name things well.

Declaring and assigning

A declaration names the type, then the variable. An assignment uses = to store a value. You can do both in one statement, which is the usual style.

C# Declare, assign, change

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The = sign is assignment, not mathematical equality. score = score + 5 is not an impossible equation: the right side is calculated first (10 + 5), then the result is stored back in score. Comparing two values uses ==, which belongs to Operators.

You can declare several variables of the same type in one statement, separated by commas. It is legal, but one declaration per line reads better:

C#
int width = 4, height = 3;   // legal
int depth = 2;               // usually clearer

The compiler also enforces types. This does not compile:

C#
int age = "twelve";   // error CS0029: Cannot implicitly convert type 'string' to 'int'

Errors like this are a gift: you learn about the mistake while typing, not when a customer does.

Definite assignment

In some languages, an uninitialized local variable contains garbage. C# refuses to let that happen. The definite assignment rule says: before you read a local variable, the compiler must be able to prove that it has been assigned on every possible path. If it cannot prove that, it reports error CS0165.

C# Use of unassigned local variable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler reports error CS0165: Use of unassigned local variable 'total'. It cannot know the condition is always true, and the rule does not try to be clever, so it assumes the if might be skipped. Two common fixes: give the variable a value at the declaration (int total = 0;), or add an else branch that assigns it as well, so every path assigns.

The rule applies to local variables. Fields of classes and elements of arrays get default values automatically, as you will see below.

var and type inference

When the right side of a declaration makes the type obvious, you can write var instead of the type name. The compiler works out the type and fixes it permanently. var is not dynamic typing, and not a "variant" like in some other languages: after the declaration, the variable has an ordinary static type.

C# var infers a static type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Three rules follow from "the compiler must infer the type":

  • var needs an initializer: var x; is error CS0818, because there is nothing to infer from.
  • var cannot be initialized with null alone (var x = null; is CS0815), because null has no type of its own.
  • var works only for local variables (and some loop and using variables). You cannot use it for fields, parameters or return types.

When to use var

Most C# teams follow this guideline: use var when the type is obvious from the right-hand side, and write the type when it is not.

C#
var customers = new Dictionary<int, string>();   // type repeated on the right: use var
var total = CalculateTotal();                    // what type? unclear: consider writing it
decimal total2 = CalculateTotal();               // better for readers

The first line saves noise (without var you would write Dictionary<int, string> twice). The second hides information from a reader who has not memorized CalculateTotal. IDEs can show inferred types as you hover, but code is also read in code reviews and on web pages, where there is no hover. Your team's .editorconfig can enforce a choice; see The dotnet CLI, Projects and Tooling.

There is one more reason to be careful: var takes the exact type of the expression, and sometimes that is not the one you meant:

C# var takes the exact type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

7 / 2 is integer division and gives 3, whatever the target type is; to get 3.5 one operand must be a double (7 / 2.0). The lesson on integer types goes deeper.

Default values

If a variable is not a local, nobody forces you to assign it. Fields in classes and structs, and elements of new arrays, start with the default value of their type: all bits zero. The default keyword gives you that value anywhere.

C# Defaults of the basic types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Numbers default to 0, bool to false, char to the null character '\0', and every reference type (such as string) to null. Because reference types default to null, a string field that nobody sets is null, and that is the root of many NullReferenceException bugs. Nullable reference types, covered in Nullable Reference Types, make the compiler warn you about it.

Notice the class Inventory is declared after the top-level statements. In a file with top-level statements, type declarations must come at the end, otherwise you get error CS8803.

Scope and lifetime

A variable's scope is the region of code where its name is valid. In C# that region is the block ({ ... }) in which it is declared, from the declaration to the closing brace. When the block ends, the name disappears.

C# Block scope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# is stricter than some languages about shadowing. A local variable cannot reuse the name of another local variable that is still in scope in an enclosing block; that is error CS0136. So this is rejected:

C#
int level = 1;
{
    int level = 2;   // error CS0136: 'level' conflicts with the outer variable
}

You can, however, declare a variable with the same name in two separate blocks, as in two different loops. Declare variables as close as possible to where you first use them, and keep them in the smallest scope that works. A narrow scope means fewer lines where the value can be changed by accident.

Scope is a compile-time idea. The related idea of lifetime (how long the value actually lives in memory) is covered in Value Types and Reference Types.

Naming variables

The compiler accepts letters, digits and underscores, but a name cannot start with a digit or be a keyword (int class = 1; fails; @class works but is rarely wise). C# is case-sensitive, so Score and score are different names. Follow the community conventions:

  • camelCase for local variables and parameters: totalPrice, userName.
  • PascalCase for types, methods and properties; _camelCase for private fields.
  • Names describe meaning, not type: age, not intValue; customers, not list1.
  • Avoid abbreviations nobody knows; a loop counter named i is the accepted exception.
  • Booleans read well as questions: isReady, hasDiscount.

Discards

Sometimes a method returns a value you do not need. A discard, written _, tells the compiler (and the reader) you are ignoring it. A discard is not a variable: you cannot read it back.

C# Discards and tuple deconstruction

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Discards appear again in switch expressions, lambdas and tuple deconstruction. Writing _ = Method(); is also how you tell analyzers "I know this returns something and I am ignoring it on purpose".

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the definite assignment rule require?

    The compiler must prove a local variable has a value on every path before you read it; otherwise it reports CS0165.
  2. 2. Which of these lines compiles?

    var needs an initializer with a type. Without one (x) or with only null (y) the compiler cannot infer the type.
  3. 3. What is the value of the double variable d after: double d = 9 / 2;

    9 / 2 is integer division and yields 4 before the result is converted to double, so d is 4 (printed as 4).
  4. 4. What is the default value of a string field that was never assigned?

    All reference types, including string, default to null. An empty string must be assigned explicitly.
  5. 5. What is a discard?

    A discard (_) lets you ignore an out value, a tuple element or a returned value without creating a usable variable.

Summary

  • A variable has a fixed static type, declared once and checked by the compiler; = assigns, == compares.
  • Locals must be definitely assigned before they are read (error CS0165 otherwise); fields and array elements start with the type's default value.
  • var infers the exact type from the initializer, needs an initializer and works only for locals; use it when the type is obvious.
  • Defaults: numbers are 0, bool is false, char is '\0', and reference types are null.
  • Scope is the enclosing block; C# forbids reusing the name of a local that is still in scope (CS0136). Declare variables close to first use.
  • Name locals in camelCase with meaningful words; use _ to discard values you do not need.

Next: Constants and readonly