Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization expression in c#

Tags:

c#

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?

like image 823
Harsha Avatar asked Sep 12 '11 18:09

Harsha


People also ask

What is initialization expression?

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.

How many types of initialization are there in C?

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.

What is initialization of array in C?

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.

What are the two types of initialization?

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.


2 Answers

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

like image 165
sll Avatar answered Sep 20 '22 07:09

sll


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;
like image 26
Jon Skeet Avatar answered Sep 23 '22 07:09

Jon Skeet