Var keyword in C# | C# Bangla Tutorial | Advanced C#


What Does “var” Mean In C#?

var data type was introduced in C# 3.0. var is used to declare implicitly typed local variable means it tells the compiler to figure out the type of the variable at compilation time. A var variable must be initialized at the time of declaration.
            var i = 100;            
            var j = "Welcome to Tutlane";            
            var k = true;            
            var l = 20.50;

Restrictions
1. Variables declared by using var cannot be used in the initialization expression.
2. Var cannot be used on fields at class scope.
3. The variable cannot be initialized with a null value.
4. Var typed variables cannot be used as method parameters.
5. Don’t use var for simple local variable types that are known to you.


When to use var


Use of var when you’re not sure what type of data will be stored in a variable.
The var was created to handle declarations when the type is not known, such as generic types, lambdas, and query expressions.
Use in anonymous types and anonymous collections.

Post a Comment

Previous Post Next Post