Loading ...

VAR in C#

Who is online?  0 guests and 0 members
home  »  forums   »  asp.net topics   »  getting started / general asp.net   » VAR in C#

VAR in C#

Posts under the topic: VAR in C#

Posted: 10/25/2010

Contributor 2237  points  Contributor
  • Joined on: 9/24/2009
  • Posts: 172

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.


tags VAR, C#

Posted: 10/25/2010

Professional 8505  points  Professional
  • Joined on: 5/3/2010
  • Posts: 391
  Answered

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.


Posted: 10/25/2010

Professional 8338  points  Professional
  • Joined on: 4/15/2009
  • Posts: 424
  Answered

mohit said:

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?

 


Page 1 of 1 (3 items)