Learn basic C# operators with examples

Hey there! 👋 So, you’re diving into C#? Awesome! Let’s start with the basic operators. These are the building blocks you’ll use every day when you’re coding. You have learned variables and data types in the previous chapter, and now, we’ll move on to operators. They help you do simple tasks like adding numbers, checking if two things are equal, or even changing a value.

Arithmetic Operators

First up, we’ve got the arithmetic operators. These are like the math tools in your toolbox. You use them for things like addition, subtraction, and multiplication. For example:
  1. + for adding
  2. - for subtracting
  3. * for multiplying
  4. / for dividing
  5. % for getting the remainder after division

Comparison Operators

Now, let’s talk about comparison operators. These help you compare two values. You might ask, “Is this number bigger than that one?” or “Are these two things equal?” Here’s what you can use:
  1. == checks if things are equal
  2. != checks if things are different
  3. > checks if something is bigger
  4. < checks if it’s smaller
  5. >= and <= check for “greater than or equal to” or “less than or equal to”

Logical Operators

Next up, logical operators. These help you combine conditions. For example, you can check if two things are true at the same time, or if one is true or the other is true. Here’s what you’ll use:
  1. && means “and” (both conditions must be true)
  2. || means “or” (at least one condition must be true)
  3. ! means “not” (it flips the value)

Increment and Decrement Operators

Ever need to add or subtract 1 from a number? Increment and decrement operators are your friends here:
  1. ++ adds 1 to a number
  2. -- subtracts 1 from a number

Assignment Operators

Now, let’s look at the Assignment operator. These allow you to assign values to variables. You can also combine them with math, like this:
  1. = is the basic assignment (like x = 10)
  2. += means “add and assign”
  3. -= means “subtract and assign”

Conditional Operator

Finally, we’ve got Conditional operators. This one is also known as the ternary operator. It’s a short way of writing an if-else statement. Here’s how it works:
  1. condition ? value_if_true : value_if_false

And that’s it for the basics! These operators will be your best friends as you write code. Once you get the hang of them, you’ll be solving problems in no time. 😎 If you’re ready to dive deeper, keep exploring – there’s so much more to learn in C#!

You will learn advanced operators in the next chapter, which covers newer C# 13.0 introduced operators. Stay tuned for more on that!

Leave a Comment

Share this Doc

Basic Operators

Or copy link