Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is There a Syntax Shortcut for Multiple Initialization in C#?

Is there a way to do this:

valueType x = 1, y = 1, z = 1;

with less characters?
e.g. When I have a large amount of state to initialize to the same starting value.
Thanks!

like image 306
Byron Ross Avatar asked Jan 14 '10 23:01

Byron Ross


2 Answers

You could try

int x, y, z;
x = y = z = 1;

But I can't see how it would help you... if you have really lots of variables you must initialize to the same thing, you could consider using some kind of collection:

var myInts = new List<int>();
for (int i = 0; i < 1000; i++)
    myInts.Add(1);
like image 162
Bruno Reis Avatar answered Sep 25 '22 20:09

Bruno Reis


If the starting value is zero and they are members of your class (not local variables) then you don't need to explicitly initialize them to zero.

Otherwise, no.

Would it make sense to use arrays instead of having a large number of parameters?

like image 34
Mark Byers Avatar answered Sep 23 '22 20:09

Mark Byers