# C# Operators

One of the first programming surprises I can remember is when I wrote this line of code in C++ many years ago…

if ( speedSetPoint = 10000) maxSpeedSet = true;

Now the intention was to run the machine at a slow 5% speed or “speedSetPoint =500” since this was a new machine installation and startup. However, that was not what happened, the speed shot past 5% and went to 100%. It was very fortunate that the rotation of the drive motor was correct or mechanical damage could have resulted.

So what happened? By using the C++ Assignment Operator “=” instead of using the Comparison Operator “==” I assigned the value of 10,000 or 100% speed to “speedSetPoint”. Using a “=” sign in an “IF’ statement will not cause a compiler error in C++ or C#. You would think by now using a “=” in an “if” statement would generate a warning, and in some compilers, it may do just that but not MS C# studio. So we have to be careful, especially during our late-night indie development sessions.

So what is the difference between Assignment and Comparison Operators? Both are used as a type of shorthand. Assignment Operators assign a value to a variable. And Comparision Operators compare the values of two variables and return a “true” or “false”**.**

Here are some Assignment Operator examples we use in Unity game development.

**“=”** this simply assigns a value to a variable **X=10;**

**“+=”** Ex… **X+=5; **is the same as **X= X+5**; which adds 5 to X and assigns the result to X.

**“-=”** Ex… **X-=5;** is the same as **X=X-5; **which subtracts 5 from X and assigns the result to X.

**“*=”** Ex…**X*=4;** is the same as **X=X*4; **which multiplies X by 4 and assigns the result to X.

**“/=”** Ex…** X/=2; **is the same as **X=X/2; **which divides X by 2 and assigns the result to X.

**“%=”** Ex… **X%=2;** is the same as **X%=2**; which divides X by 2, but assigns the value of the division remainder to X.

Here are some Comparison Operator examples we use in Unity game development.

**“==”** Ex… **if(X==100)** If X is equal to 100,the statement is true.

**“!=”** Ex…** if(X!=100)** If X is equal to 100, the statement is true.

**“>”** Ex… **if(X>Y)** If X is greater than Y, the statement is true.

**“<”** Ex… **if(X<Y)** If X is less than Y, the statement is true.

**“> =”** Ex… **while(X> =Y)** If X is greater than or equal to Y, the statement is true.

**“< =”** Ex… **while(X< =Y)** If X is less than or equal to Y, the statement is true.

This is not a complete list of all of the C# operators for the complete list check out the Microsoft C# Documentation on C# Operators and Expressions here https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/