Exercise – Perform addition with implicit data conversion
Often, you’ll want to perform mathematical operations on numeric data. You’ll start with addition in this unit, and expand to other operations in the next unit because there’s an important lesson to learn about how the C# compiler parses and interprets your code.
Add two numeric values
To add two numbers together, you’ll use the addition operator, which is the plus symbol +
. Yes, the same plus symbol +
that you use for string concatenation is also used for addition. The reuse of one symbol for multiple purposes is sometimes called “overloading the operator” and happens frequently in C#.
In this instance, the C# compiler understands what you’re attempting to do. The compiler parses your code and sees that the +
(the operator) is surrounded by two numeric values (the operands). Given the data types of the variables (both are int
s), it figures out that you intended to add those two values.
- Enter the following code into the .NET Editor:C#Copy
int firstNumber = 12; int secondNumber = 7; Console.WriteLine(firstNumber + secondNumber);
- Run the code and you’ll see the following result in the output console:OutputCopy
19