1

I have class like below.

public class Dropdown
{
    [Required(ErrorMessage = "Please select state")]
    public string StateId { get; set; }

    public List<SelectListItem> States
    {
        get
        {
            return new List<SelectListItem>() 
            { 
                new SelectListItem
                { 
                    Text = "State1", 
                    Value = "S1", 
                    Selected = false
                },
                new SelectListItem
                { 
                    Selected = false, 
                    Value = "S2", 
                    Text = "State2"
                }
            };
        }
    }
}

In Action Method, I have below two options while instantiating this class.

Approach 1

var d = new Models.Dropdown();

Approach 2

Models.Dropdown d = new Models.Dropdown();

Both are show same number of Methods/Properties/Data Members etc. I also heard that it is recommended to use Approach 1

Question

Is my assumption correct to use Approach 1 ?

leppie
  • 115,091
  • 17
  • 196
  • 297
wwcdwdcw
  • 186
  • 1
  • 8

4 Answers4

3

The var keyword is compiler feature which allows implicit type declarations - I would opt to use var purely because it's shorter.

People will probably say you lose readability using var, however, what makes

MyClass myobj = new MyClass()

any more readable than

var myobj = new MyClass()

The only scenario where I do think it does make sense to use an explicit type is when declaring an interfaced type i.e.

IMyInterface myobj = new MyClass()

Or casting

MyBaseClass myObj = new MyClass()

Then again, you could argue those cases as well because the same code would be functionality equivalent

var myObj = (IMyInterface)new MyClass()
var myObj = (MyBaseClass)new MyClass()

In general, I very rarely see the need to explicitly define the type as it's inferred by the instantiated type.

James
  • 80,725
  • 18
  • 167
  • 237
3

Both are equivalent, in fact if you write #1 the compiler will resolve it to #2. What matters then is thee readability.

There is a long debate on why var should be avoided just because it has a negative impact on readability. My opinion is that it should be avoided when possible, however in extreme cases writing an explicit type for an expression could be just too cumbersome (just write a complicated linq expression with groupping or double groupping and try to write down its type).

Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
0

There is no difference except for readability.

I'd pick Approach 1 because I consider it more readable.

Emond
  • 50,210
  • 11
  • 84
  • 115
0

for var the type is inferred. So there is no difference for both approaches from the type point of view.

As var is more readable, Stylecop suggests to use var whenever possible

Please have a look at this question to get the full information.

Community
  • 1
  • 1
Mare Infinitus
  • 8,024
  • 8
  • 64
  • 113