开发者

About c# lists send it or return it?

开发者 https://www.devze.com 2023-03-29 00:55 出处:网络
I have one question. I have to do a method that fills a List < object > from a sql database. My question is:

I have one question. I have to do a method that fills a List < object > from a sql database. My question is:

It's better to do this:

List<Product> listProducts = new List<Product>();
listProducts = loadProducts();

//this code is in ot开发者_开发问答her class
public List<Product> loadProducts()
{
    List<Product > listProduct = new List<Product> ();
    //code        
    return listProduct
}

Or it's better this:

List<Product> listProducts = new List<Product>();
listProducts = loadProducts(listProducts);

//this code is in other class
public List<Product> loadProducts(List<Product> listProduct)
{
    //Code        
    return listProduct
}

Sorry if it's a noob question but both of two works but I don't know which is more improved.

Thanks a lot.


Neither, really.

You should just go like so:

 List<Product> listProducts = loadProducts();

Option 1 makes a new list only to overwrite it later. Option 2 needlessly passes a list to the method, which will just send it back out modified.


I prefer to return it. Unless there is something with the contents of the list when you send it, I don't really see a reason to pass it as a parameter.


Go for this

List<Product> listProducts = loadProducts();

//this code is in other class
public List<Product> loadProducts()
{
    List<Product > listProduct = new List<Product> ();
    //code        
    return listProduct
}


Your first option is much better. It has clear meaning and no side effects.

Your second option will both return the list as well as fill the list that was passed to it. I would consider the filling of the list I pass to be a side effect which is undesirable.


I'd go with the first approach.

It seems somewhat pointless to pass the method a list which will then be populated and returned.


The first option is better. The second option isn't bad if you make it a void function and put the list as a reference parameter, but option one is still better because there is nothing in the original list needed for the function.


Considering that in any case you would like to pass an existing list (with stuff already there) to be incremented I like the first option since it's more readable

0

精彩评论

暂无评论...
验证码 换一张
取 消