DEV Community

mohamed Tayel
mohamed Tayel

Posted on

Mastering C# Fundamentals: Exploring Operators in C#

Meta Description: Discover the essential operators in C# with clear, detailed examples. Learn how to perform arithmetic, make comparisons, use logical conditions, and much more to enhance your programming skills in an easy yet powerful way.

In C#, operators are symbols or keywords used to perform operations on variables and values. They are essential for performing calculations, making decisions, and manipulating data. In this article, we’ll break down the different types of operators, focusing on easy-to-understand examples with clear explanations.


1. Arithmetic Operators

Arithmetic operators are used to perform basic mathematical calculations, such as addition, subtraction, multiplication, and division.

Operator Description Example
+ Adds two values a + b
- Subtracts one value from another a - b
* Multiplies two values a * b
/ Divides one value by another a / b
% Modulus - returns the remainder of a division a % b

Detailed Example:

Imagine you're a shopkeeper tracking the sales of items. You want to calculate the total price of two items, how much is left after a customer pays, and what remains if you try to split profits evenly.

int item1Price = 30;  // Price of first item
int item2Price = 20;  // Price of second item
int totalPrice = item1Price + item2Price;  // Total price = 50

// The customer pays 100, let's find the change
int payment = 100;
int change = payment - totalPrice;  // Change = 50

// Divide the total price by 2 to split it evenly
int half = totalPrice / 2;  // Half = 25

// Find the remainder when trying to divide the price by 3
int remainder = totalPrice % 3;  // Remainder = 2
Enter fullscreen mode Exit fullscreen mode

Here, we’re using the operators to perform basic math:

  • We added item1Price and item2Price using +.
  • Subtracted to find the change with -.
  • Divided the total with / to split it evenly.
  • Used % to get the remainder.

2. Assignment Operators

Assignment operators assign values to variables. The most basic one is =, but we can also combine assignments with operations like += or -= to make our code simpler.

Operator Description Example
= Assigns the value on the right to the variable on the left a = b
+= Adds the value on the right to the variable and assigns the result a += 2
-= Subtracts the value on the right and assigns the result a -= 2
*= Multiplies the variable by the value and assigns the result a *= 2
/= Divides the variable by the value and assigns the result a /= 2

Detailed Example:

Imagine a point system in a game where you update the player’s score based on actions.

int score = 100;  // Initial score
score += 50;  // Player earns 50 points, score is now 150
score -= 30;  // Player loses 30 points, score is now 120
score *= 2;   // Score is doubled, now 240
score /= 3;   // Divide score by 3, now 80
Enter fullscreen mode Exit fullscreen mode

Here:

  • score += 50 is shorthand for score = score + 50.
  • score -= 30 means subtract 30 from the score.
  • score *= 2 doubles the score.
  • score /= 3 divides the score by 3.

3. Comparison (Relational) Operators

Comparison operators compare two values and return true or false. They are commonly used in if statements for making decisions.

Operator Description Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b

Detailed Example:

Let's say we have two exam scores and want to check whether the student passed or failed.

int passingScore = 50;
int studentScore = 65;

bool passed = studentScore >= passingScore;  // true, because 65 >= 50
bool perfectScore = studentScore == 100;  // false, because 65 is not 100
bool needsImprovement = studentScore < 50;  // false, because 65 is not less than 50
Enter fullscreen mode Exit fullscreen mode

This example:

  • Checks if the student's score is greater than or equal to the passing score (>=).
  • Checks if the score is a perfect 100 (==).
  • Checks if the score is below 50 (<).

4. Logical Operators

Logical operators are used to combine multiple conditions. They return true or false based on the evaluation of the conditions.

Operator Description Example
&& Logical AND (a > b) && (b < c)
` `
! Logical NOT (negation) !(a == b)

Detailed Example:

Let’s check if a user is allowed access based on two conditions: they must be logged in and they must be an admin.

bool isLoggedIn = true;
bool isAdmin = false;

bool hasAccess = isLoggedIn && isAdmin;  // false, both conditions must be true
bool canView = isLoggedIn || isAdmin;  // true, only one condition needs to be true
bool isNotAdmin = !isAdmin;  // true, negates the value of isAdmin
Enter fullscreen mode Exit fullscreen mode
  • && requires both conditions to be true to return true.
  • || requires only one condition to be true.
  • ! negates the result (flips it from true to false).

5. Ternary Operator (Conditional Operator)

The ternary operator allows you to write if-else logic in a single line. It's concise but powerful.

condition ? expression1 : expression2;
Enter fullscreen mode Exit fullscreen mode

Detailed Example:

Suppose you want to give a discount to a customer based on their membership level:

bool isMember = true;
double discount = isMember ? 0.10 : 0.05;  // 10% discount for members, 5% for non-members
Enter fullscreen mode Exit fullscreen mode

Here:

  • If isMember is true, discount will be 0.10.
  • If isMember is false, discount will be 0.05.

Conclusion

C# operators help simplify complex logic and calculations, providing essential tools for working with data. Whether it's performing arithmetic, comparing values, or combining conditions, operators make it easy to manage and manipulate information. By breaking down these concepts into detailed and easy-to-understand examples

Top comments (0)