Why is this compiling? & # 8594; int foo = foo = 5;

Why is this line compiled?

int foo = foo = 5;

I found this on a system that I support, and I can’t understand its purpose.

+3
source share
7 answers

From = Operator (C# Reference)

The assignment operator (=) stores the value of its right operand in the storage location, property, or indexer indicated by its left operand and returns the value as the result.

Your code works as the right hand foo = 5;, and it returns 5as a value int foothat is already 5.

That's why

int foo = foo = 5;

equally

int foo = (foo = 5);

also equal

int foo = 5;
+2
source

There is no purpose. This is equivalent to:

int foo = 5;
+5
source

, :

int foo

int foo = 

foo

foo = 5

foo (5), ;

:

  • int foo
  • int foo =
  • int foo = foo = 5;
  • 5 foo 5
+2

, .

, foo = 5 5, foo. , foo 5.

, .

0

, foo 5, foo foo

foo 5.

.

:

int foo;
int bar;

foo = bar = 5;

, foo bar 5.

, ,

0

, , , , # . , :

var foo = 3;
var bar = 1;
foo = bar = 5;
Console.WriteLine("foo: {0}, bar: {1}", foo, bar); // Output: foo: 5, bar: 5
Console.ReadKey();
0

? , ; , , , .

As for “what is he doing?”, As others have said, the operator =returns its right operand, which is useful in some situations, for example. while( (line = ReadLine()) != null ). So it sets footo 5, and then sets footo 5 again ...

0
source

All Articles