Operators in C# programming language

In the previous two posts “Hello C# and .Net Core” and “Do predefined types have different values in .Net Core?”; you first learned how to print some text on a terminal panel, and then you learned how to declare the variables adding some values to them. Show the text on the terminal panel is interesting, but it is not worth it if you do not enter some user data, and assign it to the variables in your program, and use them for your estimate. In this post, we are introducing the basic operators in the C# programming language. We will also say more about other operators, just so you know that they exist, and we will learn them in some other future posts because the beginners in C# program language will be not able to understand it now. There are many things you need to learn to be able to learn all the operators in the C# programming language. So, let’s not rush.

We can assume that you learned some basic operators from elementary school math. It is important to understand that the C# programming language has a lot more operators than you have learned from mathematics. Some operators are the same as those you have learned from math while others exist only in the C# programming language, especially in version 7.0. This means that some of the operators are new and do not exist in the older version of C# programming language. See first what all operator categories exist in the C# programming language in version 7.0. See the picture:

We will start with arithmetic operators. We will start our study of arithmetic operators with a simple small program in which you need to enter two integers. The program should accept user input and execute five arithmetic operations and display results.

Start Visual Studio Code, click the File menu, and then click Open Folder. Before you select and open a folder, create an arithmetic_operators folder and open it. Find the Terminal in the View menu, left-click on it and use development environment that will display the Terminal panel or PowerShell panel depending on whether you are using Windows, macOS or Linux operating system. Enter the following command:

dotnet new console

Wait a moment to create files for your program. Click on the Explorer panel and click on the Program.cs file and delete the following line of code:

Console.WriteLine("Hello World!");

Enter the following using directive:

using static System.Console;

Go to Main procedure and type the following command first:

Clear();

This function will delete everything in the Terminal panel and set the cursor in the first line of the terminal panel. This is the same as typing the command clear in the terminal. We will not make the title of the program since the program does not contain any menu. In previous programs, you have seen some text on the terminal panel being printed from the program. In the following lines of code, see how we ask for user input values and entered them in the variables number1 and number2.

Write("Input the first number: ");

int number1 = Int32.Parse(ReadLine());

Write("Input the second number: ");

int number2 = Int32.Parse(ReadLine()); 

You first print the text so that the user knows what you are looking for. Then you declare a variable of type integer. Since we work with integers, the integer type is a good choice. Note that you can declare a variable in the C# programming language and assign it a value when you need the same variable. Previously, variables were declared at the beginning of the block of function, but this is no longer a practice. Remember when you declare a variable; you must assign it any value. When a user enters any character in the terminal panel, it is treated as a string. No matter what number the user enters, it’s text and not a number. Therefore, the first data conversion you need to know is how to convert a string type to an integer type. For this purpose, we use the already built-in Parse method that converts a string into an integer. Enter the following lines of code:

WriteLine();

WriteLine($" {number1} + {number2} = {number1 + number2}");

WriteLine();

WriteLine($" {number1} - {number2} = {number1 - number2}");

WriteLine();

WriteLine($" {number1} * {number2} = {number1 * number2}");

WriteLine();

WriteLine($" {number1} / {number2} = {number1 / number2}");

WriteLine();

WriteLine($" {number1} % {number2} = {number1 % number2}");

WriteLine();

The string interpolation is a feature that has been added in the latest C# programming language versions. The $ character in front of the quotation marks allows you to insert curly brackets { } between quotation marks anywhere in the text. In curly brackets, you can directly insert a variable that will display its value when printing text in the terminal panel. Of course, this part of the code could have been written completely differently, but we want you to immediately learn how something should work better. You can change integer type variables to decimal type variable and use the Decimal.Parse method if you want a more accurate calculation without modules calculation. Note that this program will report an error if you forget to enter a value or a character that is not an integer number or whose value is greater than the maximum integer type value or less than the integer type minimum value. In this case, the program will not execute.

Input the first number: 18.7

Unhandled Exception: System.FormatException: Input string was not in a correct format.

   at System.Number.StringToNumber(ReadOnlySpan`1 str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)

   at System.Number.ParseInt32(ReadOnlySpan`1 s, NumberStyles style, NumberFormatInfo info)

   at System.Int32.Parse(String s)

   at arithmeticOperators.Program.Main(String[] args) in …

With the help if conditions and one loop can avoid this problem but it overcomes what you have been learning so far. But you can only avoid this error, replacing the Parse method with TryParse that will not assign a value what is not integer number in the variable. It will have a devastating effect on your result, but the program will not corrupt. That is only what you can do it for now. Change the following lines of code:

Write("Input the first number: ");

// int number1 = Int32.Parse(ReadLine());

Int32.TryParse(ReadLine(), out int number1);

Write("Input the second number: ");

// int number2 = Int32.Parse(ReadLine());

Int32.TryParse(ReadLine(), out int number2);

Our advice is that whenever you need to use the Parse method, try TryParse instead. As you can see the TryParse method uses out variables. This means that it assigns a value to some variable if the value matches the type of variable. It does this by commanding out. The variable declaration in this case was made directly in the round brackets ( ) where the arguments are. Previously you had to declare a variable first before the TryParse method, then use it as an argument to the method, but that has changed. View full program code:

using System;

using static System.Console;

namespace arithmeticOperators

{

class Program

{

static void Main(string[] args)

{

Clear();

Write("Input the first number: ");

// int number1 = Int32.Parse(ReadLine());

Int32.TryParse(ReadLine(), out int number1);

Write("Input the second number: ");

// int number2 = Int32.Parse(ReadLine());

Int32.TryParse(ReadLine(), out int number2);

WriteLine();

WriteLine($" {number1} + {number2} = {number1 + number2}");

WriteLine();

WriteLine($" {number1} - {number2} = {number1 - number2}");

WriteLine();

WriteLine($" {number1} * {number2} = {number1 * number2}");

WriteLine();

WriteLine($" {number1} / {number2} = {number1 / number2}");

WriteLine();

WriteLine($" {number1} % {number2} = {number1 % number2}");

WriteLine();

}

}

}

When you run this program, the result will be similar depending on which numbers you use.

Input the first number: 157

Input the second number: 21

 157 + 21 = 178

 157 – 21 = 136

 157 * 21 = 3297

 157 / 21 = 7

 157 % 21 = 10

You can also see this program in the video:

In the following program we will deal with assigning values ​​to variables and operator priorities. Create a new program and call it precedents. Declare three integer variables and add some value to them. Do it correctly as you should always do it, then write the same in shorter terms:

// This is the right way of declare and assign values to variables

// int a = 2;

// int b = 3;

// int c = 4;

int a = 2, b = 3, c = 4;

Add the following code and run the program to check that this works:

Clear();

WriteLine($"int a = {a}, int b = {b}, int c = {c}" + Environment.NewLine); 

When you run the program with the dotnet run command in the term panel, you will see that there is no error. Assigning variables in a shorter way works. Now look at the following code:

// This is the short way of assign values to variables when you have the same value

a = b = c = 5;

WriteLine($"a = {a}, b = {b}, c = {c}" + Environment.NewLine);

You simply have one value that you want to add to multiple variables. Then you can assign the values ​​to variables in a shorter way, but not at declaration. Variables must be declared and assigned a certain value, otherwise you cannot work. Therefore, this shorter method is not shorter as you also need to declare variables. It will rarely see you anywhere in the code. This is justified in our program. See the following code:

// Some arithmetic operations

a = b + c; // 10

b += 3; // b = b + 3 = 8

c -= 2; // c = c - 2 = 3

WriteLine($"a = {a}, b = {b}, c = {c}" + Environment.NewLine);

Notice the variables b and c. In these lines of code we used Assignment operators. When you assign only a value to a variable, you do not need to write the same variable twice. See the following picture of the assignment operator.As you can see, when working with arithmetic operators, you can use assignment operators to write code shorter. But what are the priorities? In C# programming language, operators have their priority on how they are executed. E.g. multiplication will always be performed rather than addition. Therefore, it is necessary and safer to always use parentheses before you get into the situation of getting the wrong result because of the operator’s priorities.

// arithmetic precedences

a = 7 + 3 * 10; // 37

b = (7 + 3) * 10; // 100

c = 10 * 5 / 5; // 10

WriteLine($"a = {a}, b = {b}, c = {c}" + Environment.NewLine);

You may have expected a score of 100 instead of 37. Therefore, it is always good to use round brackets ( ) for calculations, such as for variable b. Take a look at the following picture of the operator table, how operators are ranked by priority. And the program will always perform calculations according to the priorities of the operator, unless you use the brackets.

From C# programming language version 7.0, you can also use digital separators. They make it easy for you to read the numbers in your code. See the following code:

// digit seperators

a = 1000000;

b = 1_000_000; // use digit seperators because easier reading numbers

c = 0xF_42_40;

WriteLine($"a = {a}, b = {b}, c = {c}" + Environment.NewLine);

As you can see the variable is hard to read at first glance. Imagine being a variable and a much larger number, then you would have to count zeros to read the number. Thanks to a digital separator you can use one or more separators in any number. Variable b is easy to read. As you can see, variable c can accept the number in hexadecimal instead of decimal, but will always display it in decimal in the terminal panel. It is interesting here that you can use a digital separator in hexadecimal numbers but even in binary ones. See what the whole program code looks like.

using System;

using static System.Console;

namespace precedence
{

class Program

{

static void Main(string[] args)

{

// This is the right way of declare and assign values to variables

// int a = 2;

// int b = 3;

// int c = 4;

int a = 2, b = 3, c = 4;

Clear();

WriteLine($"int a = {a}, int b = {b}, int c = {c}" + Environment.NewLine);

// This is the short way of assign values to variables when you have the same value

a = b = c = 5;

WriteLine($"a = {a}, b = {b}, c = {c}" + Environment.NewLine);

// Some arithmetic operations

a = b + c; // 10

b += 3; // b = b + 3 = 8

c -= 2; // c = c - 2 = 3

WriteLine($"a = {a}, b = {b}, c = {c}" + Environment.NewLine);

// arithmetic precedences

a = 7 + 3 * 10; // 37

b = (7 + 3) * 10; // 100

c = 10 * 5 / 5; // 10

WriteLine($"a = {a}, b = {b}, c = {c}" + Environment.NewLine);

// digit seperators

a = 1000000;

b = 1_000_000; // use digit seperators because easier reading numbers

c = 0xF_42_40;

WriteLine($"a = {a}, b = {b}, c = {c}" + Environment.NewLine);

}

}

}

 

When you run this program with the dotnet run command in the terminal panel, the result will be as follows:

int a = 2, int b = 3, int c = 4

a = 5, b = 5, c = 5

a = 10, b = 8, c = 3

a = 37, b = 100, c = 10

a = 1000000, b = 1000000, c = 1000000

You can also see this program in the video:

Because programming often requires the variable to be incremented or reduced by 1, especially when working with loops, there has been a need to create operators that will increase or decrease the variable by 1. Therefore, we use increments and decrements operators. Let’s create one program that will best explain this to us. This is the code of the entire program. Check out the namespace name to know what the program is called:

using System;

using static System.Console;

namespace increment_decrement
{

class Program

{

static void Main(string[] args)

{

Clear();

Write("Enter an integer number: ");

Int32.TryParse(ReadLine(), out int number);

WriteLine();

WriteLine($"\nYour number is: {number}");

WriteLine();

WriteLine($"\nYour number {number} after post-increment ( x++ ): {number++}");

WriteLine($"\nYour number {number} after post-decrement ( x-- ): {number--}");

WriteLine($"\nYour number {number} after pre-increment ( ++x ): {++number}");

WriteLine($"\nYour number {number} after pre-decrement ( --x ): {--number}");

WriteLine();

}

}

}

As you can see in the code, there are two ways to increase the number by 1 and two ways to reduce the number by 1. But there is a trick.

  • Post – Increment  X++
  • Pre – Increment  ++X
  • Post – Decrement  X–
  • Pre – Decrement  –X

So, let’s first analyze the program and its results. If you run the previous program, your result will be similar depending on your input data.

Enter an integer number: 10

Your number is: 10

Your number 10 after post-increment ( x++ ): 10

Your number 11 after post-decrement ( x– ): 11

Your number 10 after pre-increment ( ++x ): 11

Your number 11 after pre-decrement ( –x ): 10

In the seventh line of code in the Main procedure, we see that the program printed the variable number value and then incremented. That is why you see the same value of you; which is not to say that the increment war not executed. In the case of decrements, the matter is repeated; the program first prints the value, then executes the decrement. Such increment and decrement is more precisely called suffix increment and decrement. It is mainly used in loops. Therefore, when you want to display the result of increment or decrement, use prefix increment or decrement where increment or decrement is first executed and then the value is displayed.

You can also watch this program in the following video:

However, what are comparison operators? Comparison operators, also known as relational operators, are essentially binary operators that validate the conditions of two operands and return a boolean-type logical value; true or false depending on whether the condition is met. They are often used in coding, especially in conditional expressions and loops. The comparison operators are:

  • == … isto
  • !=  … različito
  • <   … manje
  • <= … manje i jednako
  • >= … veće i jednako 

Take a look at the following program for how comparison operators work, despite the fact that we did not use if statements. You will often use comparison operators in if statements. You will learn if statements in the next post. For now, concentrate on comparison operators. Make the following program:

using System;
using static System.Console;

namespace comparision_operators

{

class Program

{

static void Main(string[] args)

{

Clear();

Write("Enter an integer number: ");

Int32.TryParse(ReadLine(), out int number);

WriteLine();

WriteLine($"Your number is {number}");

WriteLine($"Your number is equal 50 : { number == 50 }");

WriteLine($"Your number is greater than 50 : { number > 50 }");

WriteLine($"Your number is greater or equal 50 : { number >= 50 }");

WriteLine($"Your number is less than 50 : { number < 50 }");

WriteLine($"Your number is less or equal 50 : { number <= 50 }");

WriteLine($"Your number is inequal 50 : { number != 50 }");

WriteLine();

}

}

}


Whatever number you enter, the program will examine all the terms of comparison and show you what is true and what is incorrect. Comparison operators simply determine what is true and what is not. The result is always boolean and can only be true or false. By combining them with if statements, you determine what the flow of your programs will be. Run the program and depending on what number you enter, the result will be as follows:

Enter an integer number: 188

Your number is 188

Your number is equal 50 : False

Your number is greater than 50 : True

Your number is greater or equal 50 : True

Your number is less than 50 : False

Your number is less or equal 50 : False

Your number is inequal 50 : True

You can also see this program in the following video:

You will be teaching other operators in some of the next following posts.

 

 

 

Leave a Reply

Close Menu