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:
Syntax
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
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());
}
}
Login to try C/C++/Java/PHP code in the editor
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
- Declaring
var x;without an initial value, which is an error because the compiler cannot infer the type. - Assigning a value of another type later, such as
var n = 5; n = "five";, which fails becausenis anint. - Overusing
varwhen 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: