I have the following line of code
int i = (i = 20);
and it sets the value of i to 20. Now my question is, are the two statements same ?
int a = 0;
int i = (a = 20);
and
int a = 0;
int i = a = 20;
Both the statements will set the values as i = 20
and a = 20
. What's the difference?
If they are same then why are there braces for equating the value?
An initialization expression initializes a new object. Most initialization expressions are supported, including most new C# 3.0 and Visual Basic 9.0 initialization expressions.
There are two ways to initialize the variable. One is static initialization in which the variable is assigned a value in the program and another is dynamic initialization in which the variables is assigned a value at the run time.
The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.
Two types of variable initialization exist: explicit and implicit. Variables are explicitly initialized if they are assigned a value in the declaration statement. Implicit initialization occurs when variables are assigned a value during processing.
From MSDN:
The assignment operators are right-associative, meaning that operations are grouped from right to left. For example, an expression of the form a = b = c is evaluated as a = (b = c).
Yes, those two are the same - but I would strongly discourage you from initializing variables like this. I would much rather see:
int a = 0;
// Whatever the intervening code is
a = 20;
int i = a;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With