

Data types play very powerful role in programming, weย use data type to specify type of data to be stored in variables. But what if weย donโt know the type of values that is to be stored in variable in such scenario
var keyword used.ย ย
In C# programming variables can be declared as explicit type or implicit type. Implicitly typed local variables are strongly typed just as we declared the typed variable, but the compiler determines the type at run time depending on the value stored in it .ย
The C# var keyword is used to declare implicit type variables in C#.ย
ย Here you can see that name variable has assigned a stringย ย ย โKaushal Raoโ. So now type ofย ย ย variable name is string.
Use of โvarโ is not recommended everywhere. The var was created to handle declarations when the type is not known, such as generic types, lambdas, and query expressions. If you already know the type of a variable, you must declare that explicitly.
Remember, if you donโt declare a variable explicitly, the compiler must do extra work to determine the type. While the cost of this operation may not be significant, itโs just unnecessary burden on the compiler.
We can use var in following requirements-
The following restrictions apply to implicitly-typed variable declarations:
var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group,or an anonymous function.
var cannot be used on fields at class scope.
Variables declared by using var cannot be used in the initialization expression.
using System;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var intVar = 1;
var charVar = 'a';
var strVar = "use of var keyword";
Console.WriteLine("{0}\n{1}\n{2}", intVar, charVar, strVar);
Console.Read();
}
}
}
We can also create an array with var if we dont know the type of value to be stored in an array.
using System;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var arr = new int[] { 10, 20, 30, 40, 50, 60 };
foreach (var item in arr)
{
Console.Write(item.ToString());
}
Console.Read();
}
}
}
ย โvarโ is used to store anonymous types. The code snippet in creates and stores an anonymous type.
// author is an anonymous type
var author = new {
Name = "Kaushal Rao",
Book = "Programming in C#",
Year = 2023,
Price = 230
};
Console.WriteLine("Author details: {0}, {1}, {2}, {3}", author.Name, author.Book, author.Year, author.Price);
ยฉ 2024. All rights reserved by trueweblogic.