C# is a strongly
typed language. That means you should declare variables before using it.
It can be of explicitly typed or implicitly typed. I.e when
we know the data type of a variable you can explicitly typed it
Example:
Int a;
a=10;
or
int a=10;
but in case if you not aware of the data type of variable by
using implicitly typed manner.
Var keyword is used for that.
Var a=10;
The data type of the variable is the data type of value we
are assigning to the variable.
In the above example 10 is int type. So a is int
Var name=”Muthu karthikeyan”;
In this example “ Muthu karthikeyan” is string so the data
type of name is String.
The variable declared using var keyword is strongly typed. You
cannot change the type of variable after declaring it.
Example:
var a =10;
a=”karthikeyan”;
The above statement will throw An error that a is int type. You
cannot assign string value to integer variable.
Don’t use var keyword for declaring data type of a property and
also return type of method.
Var keyword is use full in case of linq query where we don’t know the
data type that the query will return.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string[] arr = { "muthu", "karthikeyan", "vishnu", "pradeep" };
var o = from a in arr where a.Length > 5 select new { len =
a.Length, value = a };
foreach(var v in o)
{
Console.WriteLine("name={0} length={1}",
v.value, v.len);
}
Console.ReadKey();
// Go to
http://aka.ms/dotnet-get-started-console to continue learning how to build a
console app!
}
}
}
Output:
name=karthikeyan length=11
name=vishnu length=6
name=pradeep length=7
in the above case var keyword is very usefull.
-Muthu karthikeyan.
Madurai.
No comments:
Post a Comment