← Back to C# Course | Chapter 2: Variables & Types | Lesson 1 of 7

The var Keyword

The var keyword lets C# work out what kind of thing a variable holds by looking at what you put in it. It is like a labeler that reads the item and writes the right label for you.

In this page:

  1. The var Keyword
Syntax
csharp
var variableName = initialValue;   // type is inferred at compile time

The var Keyword

var lets the compiler infer a variable's type from its initializer at compile time. The variable is still statically typed — var is not dynamic typing, it's just a shorthand for the programmer.

It must always be initialized on the same line it is declared.

Warning: var x; without an initializer is a compile error — the compiler has nothing to infer the type from.

Example: The var Keyword

markup
using System;

class Program
{
    static void Main(string[] args)
    {
        var count = 10;
        var name = "Alice";
        var price = 19.99;

        Console.WriteLine(count.GetType());
        Console.WriteLine(name.GetType());
        Console.WriteLine(price.GetType());
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Declaring var x; without an initial value, which is an error because the compiler cannot infer the type.
  2. Assigning a value of another type later, such as var n = 5; n = "five";, which fails because n is an int.
  3. Overusing var when the type is not obvious from the right-hand side, which makes code harder to read.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.