19
C# - Mathematical Operators
During programming there is always a need to add some numbers together. Whether it be ages, dates, monetary values. I'm going to show you how this can be done in C#.
The plus operator can be used in 2 scenarios in C#. It can be used to add two integers (numbers) together, but can also be used to concatenate (join) two words or sentences together.
Which can sometimes be confusing at first for code newbies.
Here we have 2 integer variables declared using the var variable declaration. This means the compiler will pick the correct variable type upon getting its value. In this case it would compile, to be an integer.
Ok, say we have two integers and we want to add them together. We create a 3rd variable called 'result' and we assign the value of 'x + y', to it. The code takes the "+" operator and adds the two variables together, resulting in 'result = 5'.
So ok say we have two variables such as greeting and name; We have a website or application in which we want to display the Greeting, with the name of the user logged in. However the time of the day can change, meaning the greeting may change too. Rather than having multiple combinations of the name + greeting, we can just pass in 2 variables and then combine them.
Lets take a look with an example:
Here you can see we've took the two variables, and then added them together with the an empty string shown with " ".
Otherwise we'd end up with Good MorningGrant, which is not readable. There are many other ways of joining strings together, but that will come in later tutorials around string manipulation.
Subtracting in C# is different to the addition operator, in the sense you can't manipulate strings. You can only manipulate numerical values.
We do this using the "-" operator. Makes sense right?
It can be used like so:
Division is carried out using the "/" operator.
Simply place the operator between two values or variables and the output will be calculated like so:
Note: in C# if you use the var keyword to declare your number, and perform a division calculation, expecting a decimal result,you will not get that!
When coding you may want to check the remainder value after you've divided. This is particularly useful when wanting to know if a number is exactly divisible by another.
Whys that, I hear you ask? Because the C# compiler will automatically infer the variables as being of type integer. It will then perform an integer division, meaning that it will return an integer value, like so :
In this situation you can use the modulus operator. This is the % sign in C#. This operator perform a division calculation and return the remainder value.
This can be used as shown below:
U can use the * multiplication operator, to perform multiplication calculations.
Simply place it between two numbers.
Now let's see it all put together:
19