开发者

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!


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


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?


in general I think it tends to be better to separate each declaration. It tends to make it easier to change around later.

especially when lots of variables tend to suggest that they should be combined into another object.

so I'd tend to do...

valueType  x = IntialValue;
valueType  y = IntialValue;
valueType  z = IntialValue;

etc...


Lets say all your "variables" are actually fields of a POCO (plain old CLR object, that is, and object that serves no purpose but to hold data).

class State {
    public double pression_top;
    public double pression_bottom;
    /* hundreds and hundres of fields */
}

In that case, you could do something like:

var myState = new State();
var t = typeof(State);
foreach (var field in t.GetFields()) {
    field.SetValue(myState, 1);
}

Note however that this code is not optimized, and not very concurrency-friendly.


I wanted to add a fun fact and remind ourselves that many basic principles are still used in modern languages. This example is from "The C Progamming Language" book (1988) and also valid in C# language:

nwhite = nother = 0;
for (i = 0; i < 10; ++i)
    ndigit[i] = 0;

A nice example by showing that you can assign a value as single expression to variables if few and better make a collection if many.

Also, the initialization nwhite = nother = 0; can be written in formula:

xval = (yval = (zval = 0));;

Because assignment operator is right-associative (performed from right to left) and we can write the expression elegantly without parentheses.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜