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 ints), it figures out that you intended to add those two values.

  1. Enter the following code into the .NET Editor:C#Copyint firstNumber = 12; int secondNumber = 7; Console.WriteLine(firstNumber + secondNumber);
  2. Run the code and you’ll see the following result in the output console:OutputCopy19

visual studio net training courses malaysia

Leave a Reply

Your email address will not be published. Required fields are marked *