user2740190
user2740190

Reputation:

When do we need to create an object with "new" and when can we just declare and assign value to it?

More specifically in a LINQ to Entities query:

List<string> myResult = (from myTable do some joins...blah).ToList();
if(myResuly.Any())
{
 // Foo
}

My question is how do we know if we can use

List<string> myResult = (from myTable do some joins...blah).ToList();

or we should use:

List<string> myResult = new List<string>();
 myResult = (from myTable do some joins...blah).ToList();

Upvotes: 0

Views: 109

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186708

We should never use (though it's safe) the code like that:

  List<string> myResult = new List<string>();
  myResult = ... // myResult is reassinged here and "new List<string>()" just lost

since you're just creating useless List<string> instance. Put instead

  List<string> myResult = WhatEver(...).ToList();

Upvotes: 1

kockburn
kockburn

Reputation: 17616

If you can already get the list why waste an extra line of code?

List<string> myResult = new List<string>();

The whole idea of initializing your list, is that you don't already have one that you can stock in 'myResult'.

Imagine trying to access your list that you haven't initialized yet.

Upvotes: 1

Robert Levy
Robert Levy

Reputation: 29073

If there is a function on the right side of the = that is generating the value, you don't need new. In your 3rd example, the list you new is immediately thrown away and the one returned by ToList() is used in it's place

Upvotes: 2

Related Questions