Now a day I am playing my role as a panel member of .NET
interview team. Rely I am enjoying this in middle of development. Sometime I ask
one question “What is Var keyword in C# ?”
Answer comes in different flavor. Some of them are
Var keyword is to declare variable in C#.
We use var keyword in LINQ, But don’t know exact what is it
etc etc.
So ,What is Var ?
In .NET 3.0 the concept of var is introduce. Yes, it is use
to declare variable.when you don’t know exact type of your data. Means use var keyword to declare
variable when you are unaware about data type of your variable. And compiler
will take care rest of the thing in compile time ( rest of the thing mean “conversion
from raw week type to strong type”). Hmm… not understanding ??
Ok ,Let’s have one example.
static void Main(string[] args)
{
var a = 10;
Console.Write(a.GetType());
Console.ReadLine();
}
In output in am calling GetType() function to get type of a.
And in output it clearly showing ,type of a is Inet32. Now question is .
I did’n declare a as interger variable. Who has done this
job ? yes compiler.
Now you probably thinking . When compiler is converting?
Compiler is making it strong type in compile time. Not in
run time…. Don’t accepting ? ok . Let me show it.
class Program
{
static void Main(string[] args)
{
var mylist = new List<int>();
mylist.Add(100);
}
}
And this is the screen when I was calling to Add() function
Now you can clearly see that mylist object is showing Add()
function in time of writing program.
No comments:
Post a Comment