简体   繁体   中英

operator '+' is ambiguous on operands of type 'ulong' and 'int'(C#)

I'm trying to add a ulong(Uint64) to a normal int value ,it gives me the error in the title (I'm using visual studio 2015 community) I have also tried casting all of it into ulong but it still doesn't work here is some example code

ulong balance = 0;
int salary = 5;
private void button_click()
{
     //this is what the error refrences:
     balance = balance + salary;
     //here's when I try to cast(gives the same error):
     balance = (ulong)(balance + salary);
     console.writeline("your balance is now : " + balance.tostring());
}

whichever the operator is (/,+,*,-) it still gives the same error :/ I have searched all over the place and can't find anything that solves this I have checked over 7 pages on msdn and no, Nothing :(

I just want to know how to add , subtract ,divide or multiply them , and thank you :)

The problem is that you have casted the outcome of balance + salary instead of casting salary to ulong to match balance type.

This should suffice:

balance += (ulong)salary;

If you want to use up less memory, you can cast salary to uint instead of ulong (32-bit integer vs 64-bit integer). Of course it does make sense in some really rare scenario (large amount of data and not so much memory). Also you need to take in account that casting signed integer to unsigned one can result in some (un)expected behaviour.

You could cast int to ulong while adding:

balance += (ulong)salary;

Or in the long form:

balance = balance + (ulong)salary;

The problem is that Ulong is always positive while an int is not. But its fine to cast salary as a uint as well and then add them.

This makes sense and gives no warnings.

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