简体   繁体   中英

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();

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

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM