What is this syntax???

  • Thread starter Thread starter Jesper, Denmark
  • Start date Start date
J

Jesper, Denmark

double c = double.NaN;

Console.WriteLine(c = 10);
Console.WriteLine(c += 5);
Console.WriteLine(c);

output:
10
15
15

Question: Has it always been possible to do these assingments and
operations, and how can such an operations return a value?? I like it, but
thought that this kind of operations were nice candy back from my c++ days
and not allowed in c#.

regards Jesper.
 
Jesper said:
double c = double.NaN;

Console.WriteLine(c = 10);
Console.WriteLine(c += 5);
Console.WriteLine(c);

output:
10
15
15

Question: Has it always been possible to do these assingments and
operations, and how can such an operations return a value?? I like it, but
thought that this kind of operations were nice candy back from my c++ days
and not allowed in c#.

What you have inside of the first two WriteLine() calls is an assignment
expression. So
c = 10
assigns 10 to c and evaluates to the assigned value, similar
c += 5
inrements c by 5 and evaluates to the assigned value.
 
The logical result of any assignent is the value that was assigned. So
this behaves as expected. This also allows the abbreviated syntax:

obj.Foo = obj.Bar = true;

where true is assigned to Bar and Foo (Bar is not queried at any point;
the result of the first assignment (true) is used for the second
assignment).

Marc
 
Jesper said:
double c = double.NaN;

Console.WriteLine(c = 10);
Console.WriteLine(c += 5);
Console.WriteLine(c);

output:
10
15
15

Question: Has it always been possible to do these assingments and
operations, and how can such an operations return a value?? I like it, but
thought that this kind of operations were nice candy back from my c++ days
and not allowed in c#.

They are allowed in C#.

Your examples are not examples of where it makes sense.

But you will see the following a lot:

string line;
while((line = sr.ReadLine()) != null)
{
....
}

And it is using the same feature.

Arne
 
Question: Has it always been possible to do these assingments and
operations, and how can such an operations return a value?? I like it, but
thought that this kind of operations were nice candy back from my c++ days
and not allowed in c#.

Quite the opposite; the usage is expanding: not only are they allowed in C#,
but as of the first version of VB.NET the syntax was added to that language
too!
 
VB has never allowed assignments within expressions.

Sorry, I was only referring to the <operator>= syntax (for standalone
assignments). Obviously I was unclear.
 
Back
Top