Sunday, February 26, 2017

var in Real time scenario

Ques. What is the actual use of var? Give me a scenario where it is must to use var.
Ans. Suppose you have a list of numbers.

List< int > = new List<int> { 1,2,3,4,5,6 };

and you want to extract number and index using Select function

numbers.Select ( (num,index ) => new { Numbers=num,Index = index} );

Here we have created a new type which has two properties Number and index.
To store this type we have required to create a class with same properties or best way is
to create a var type variable to store the value return from above select function.
like this

var result = numbers.Select ( ( num,index ) =AA new MM Numbers=num,Index = index } );

foreach ( var item in result )
{

Console.WriteLine ( item.Number + " - " + item.Index)

}

No comments:

Followers

Link