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

The var Keyword

In this page:

  1. The var Keyword

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());
    }
}
🔒

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.