Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialising multiple empty lists

Tags:

c#

Simple syntactic c# question is this.

Given this code:

List<string> Columns = new List<string>();
List<string> Parameters = new List<string>();
List<string> Values = new List<string>();

It can be reduced to:

List<string> Columns = new List<string>(), Parameters = new List<string>(), Values = new List<string>();

But can I get it shorter still, since they're all being initialised to an empty list?

Thank you all!

like image 421
Adrian Hand Avatar asked Jul 10 '26 17:07

Adrian Hand


2 Answers

I can recommend to use var keyword if these variables are not class fields, because types are know from usage. It really makes no sense to flat declaration of three variables.

var Columns = new List<string>();
var Parameters = new List<string>();
var Values = new List<string>();

Yes, you can do things, like declaring multiple local variables in one line and then initializing them in one line. But please, avoid declaring multiple variables in one line - it makes code much readable.

like image 128
Ilya Ivanov Avatar answered Jul 14 '26 10:07

Ilya Ivanov


Purely as a point of trivia/code golf:

Func<List<string>> n = () => new List<string>();
List<string> a = n(), b = n(), c = n(), d = n(), e = n(), f = n();

But it would be ridiculous to use this in place of the much clearer constructs available. It might have value if the initialization was more complex, and the code was properly named and spaced.

Func<List<string>> setupFoo = () => {
    return new List<string>() { 1, 2, 3 };
};

var option1 = setupFoo();
var option2 = setupFoo();
var option3 = setupFoo();
like image 41
Tim M. Avatar answered Jul 14 '26 11:07

Tim M.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!