Posted: 10/25/2010
Hello Experts,
There is a class(Test).
Class Test()
{
Test()
Console.WriteLine("Welcome");
}
static void Main()
Test obj = new Test(); .........1
var obj = new Test(); ...........2
I can create instance of Test class to use both 1 and 2 line. Can anyone tell me what is difference between above both line and why, where should we use VAR?
Thanks in advance.
First of all, there is no difference in the result since both objects end up to be of type Test.
I would recommend to use VAR if you think the object will be a local variable, instantiated locally and used only locally.
Var is also good to be used when you are not sure about the returning type which is assigned to the variable. This adds additional flexibility in the code and additional type-safety.
On the other hand, don't use VAR if you know what type you are expecting.
So, part of the choices can be made by yourself since there is no real big difference. It's good practice to use VAR when working with LINQ, but if you know that you are instantiating object of a class like
Test obj = new Test(), then VAR is not needed at all ;).
Hope this helps.
mohit said: user="mohit kumar"]where should we use VAR?
user="mohit kumar"]where should we use VAR?
As Hajan stated, use Var only when its required. Here's an interesting article that you might want to read:
Can the C# Var Keyword be Misused?