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:+
for adding-
for subtracting*
for multiplying/
for dividing%
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:==
checks if things are equal!=
checks if things are different>
checks if something is bigger<
checks if it’s smaller>=
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:&&
means “and” (both conditions must be true)||
means “or” (at least one condition must be true)!
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:++
adds 1 to a number--
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:=
is the basic assignment (likex = 10
)+=
means “add and assign”-=
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 anif-else
statement. Here’s how it works:
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!