4

Sorry for this stupid question, but I can't find answer for it. So, why I can't write code like this in C#:

int a = 10, b = 20, c = 30, d = 40; a = b, c = d; 

In C++ I can write it and it will be ok.

Why it doesn't compile in C#?

3
  • Why not just try: int a = b, c = d; if you want to get rid off of the values of a and c? Commented Sep 19, 2014 at 19:09
  • You write: a = b; c = d; in C# Commented Sep 19, 2014 at 19:15
  • @Surya I just want to clarified my quesion by example. Maybe it's not very good. But i try to focus on second line. Commented Sep 19, 2014 at 19:22

3 Answers 3

12

You can write the first line. That is allowed in C#, and spelled out in section 8.5.1 of the C# Language Spec, where it shows that each local-variable-declarator can be in a list that's comma separated:

local-variable-declarators: local-variable-declarator local-variable-declarators , local-variable-declarator 

However, C# does not have a comma operator like C++, so you have to split the second line:

int a = 10, b = 20, c = 30, d = 40; a = b; c = d; 
Sign up to request clarification or add additional context in comments.

4 Comments

Can you explain, what mean comma operator in C#? Why i can initializate varibale by comma, write statements in for but can't write such code?
@NikitaSivukhin There is no comma operator in C#. The only reason that's legal in C++ is that there is an operator in that language which allows multiple expressions to be placed where a single expression is expected (the C++ comma operator). That operator doesn't exist in C# - it's just not part of the language.
Why i can write i = x, j = y in this code: for (int i = 0, j = 0;; i = x, j = y) {...} This is special design for "for"?
@NikitaSivukhin Yes - For loops allow a "statement-expression-list" (the list is key) in C#.
3

Simply because C# is not C++, and the two languages are different from one another.

Or, more precisely: The C# language is not a superset of the C++ language. Therefore not every C++ program is a valid C# program.

Comments

1

The first line is just fine. However, the second line consists of two separate statements. Statements have to be separated by a semicolon ;.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.