简体   繁体   中英

Can't use += in c#?

My class has just switched to c# from java so I am still learning its syntax. It might sound a stupid question, but im stuck for an hour now without answer to a simple question, is there += in c#?

for (int i = 0; i < users.Count(); i++) {
            double sum += users[i].getFine();

it gives me and error at sum += part saying:

"Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement"

You should first define your variable and then try to alter it using +=

double sum=0;
for (int i = 0; i < users.Count(); i++) 
    sum += users[i].getFine();

sum += x; equals to sum = sum + x ;

You can learn more of it at MSDN += Operator (C# Reference)

I hope this simple answer turns out to be helpful.

It is working as it should be.

This:

 double sum += users[i].getFine();

is equal to

double sum =  sum + users[i].getFine();

And sum does not exist at the moment you try to add it to users[i].getFine . The error you are getting means, that compiler has no idea about what you are trying to do - you should assing something to a variable, or increment other, or await something, or do any of other things in this message.

Also, this code would not work as expected anyway, as it is being rewritten at every loop. The sum should be defined outside of the loop.

What do you think your posted code would do as below. Essentially on every loop iteration you are declaring a new variable double sum and in such case the code sum += users[i].getFine(); does it make sense at all. NO, it's meaning less and logic less. Thus compiler throwing the error asking you to declare the variable sum out of loop scope.

for (int i = 0; i < users.Count(); i++) {
            double sum += users[i].getFine();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM