C# Operators
In C#, operators are unique symbols utilized to execute actions on variables and values known as operands. Operators are fundamental elements in every programming language. They can act on one or more operands to conduct operations and generate an outcome. They can carry out various tasks like arithmetic calculations, assigning values, bitwise operations, and logical evaluations.
Simple C# Operator Example:
Let's consider a basic example to demonstrate operators in C# programming language.
Example
using System;
class BasicExample {
static void Main() {
int a = 10, b = 20;
int c = a + b;
Console.WriteLine("The value of a + b is " + (c)); // Addition
}
}
Output:
The value of a + b is 30.
Types of Operators:
There are several types of operators that may perform different types of operations in C#. Important C# operators are as follows:
- Arithmetic Operators
- Relational Operators
- Logical Operators
- Bitwise Operators
- Assignment Operators
- Unary Operators
- Ternary or Conditional Operators
- Null-Coalescing Operators
- Operator Associativity and Precedence
Here, we will explore each of these operators individually, detailing their various types and providing illustrative examples.
1. Arithmetic Operators
In C#, arithmetic operators are primarily utilized for executing fundamental mathematical calculations (such as addition, subtraction, multiplication, division, etc.) on the operands.
| Operator Name | Symbol | Description |
|---|---|---|
| Addition | + | It is commonly utilized to add two numbers together. |
| Subtraction | - | It is commonly utilized to subtract one number from another. |
| Multiplication | * | It is commonly utilized to multiply two numbers. |
| Division | / | It is commonly utilized to divide one number by another. |
| Modulus | % | It returns the remainder of division. |
C# Arithmetic Operators Example:
Let's consider a scenario to demonstrate the arithmetic operators in C#.
Example
using System;
class Arithmetic {
static void Main() //main method
{
int a = 10, b = 3; //initializing variables and values
Console.WriteLine("The value of a + b is " + (a + b)); // Addition
Console.WriteLine("The value of a - b is " + (a - b)); // Subtraction
Console.WriteLine("The value of a * b is " + (a * b)); // Multiplication
Console.WriteLine("The value of a / b is " + (a / b)); // Division
Console.WriteLine("The value of a % b is " + (a % b)); // Modulus
}
}
Output:
The value of a + b is 13
The value of a - b is 7
The value of a * b is 30
The value of a / b is 3
The value of a % b is 1
2. Relational (Comparison) Operators
In C#, a relational operator is primarily used to compare two values and produces a boolean outcome (either true or false).
| Operator Name | Symbol | Description |
|---|---|---|
| Equal to | == | It checks both operands are equal to one another. If both operands are equal, it returns true; else return false. |
| Not equal to | != | It checks if the values of two operands are equal or not. If the values are not equal, the condition becomes true. If values are equal, the condition becomes false. |
| Greater than | > | It is utilized to compare two values and returns true if the first operand is greater than the second. If the first operand is not greater than the second, it returns false. |
| Less than | _PRESERVE26__= | It returns true if the first operand is greater than or equal to the second operand. Otherwise, it returns false. |
| Less than or equal to | _PRESERVE27__> | It shifts all bits of a number to the right by a defined number of positions. In order to positive numbers, empty bits are filled with 0. In order to negative numbers, the behaviour depends on the implementation. |
C# Bitwise Operators Example:
Let's consider a scenario to demonstrate the bitwise operators in C#.
Example
using System;
class Bitwise
{
static void Main() //main function
{
int a = 10, b = 15; //initializing variables and values
Console.WriteLine("The value of a & b is " + (a & b)); // Bitwise AND
Console.WriteLine("The value of a | b is " + (a | b)); // Bitwise OR
Console.WriteLine("The value of a ^ b is " + (a ^ b)); // Bitwise XOR
Console.WriteLine("The value of ~a is " + (~a)); // Bitwise Complement
Console.WriteLine("The value of a << b is " + (a << 1)); //Bitwise Left Shift
Console.WriteLine("The value of a >> b is " + (a >> 1)); //Bitwise Right Shift
}
}
Output:
The value of a & b is 10
The value of a | b is 15
The value of a ^ b is 5
The value of ~a is -11
The value of a << b is 20
The value of a >> b is 5
5. Assignment Operators
In the C# programming language, assignment operators play a crucial role in assigning values to variables and conducting operations simultaneously. Among these operators, the most frequently utilized one is the assignment operator (=), which enables the alteration of the stored variable value.
| Operator Name | Symbol | Description |
|---|---|---|
| Assign | = | It is commonly utilized to assign the value of the right operand to the left operand. |
| Add and assign | += | It allows us to add the right operand to the left operand and assign the result value to the left operand. |
| Subtract and assign | -= | It allows us to subtract the right operand from the left operand and assign the result value to the left operand. |
| Multiply and assign | *= | It allows us to multiply the left operand by the right operand and assign the result number to the left operand. |
| Divide and assign | /= | It allows us to divide the left operand by the right operand and assign the result value to the left operand. |
| Modulus and assign | %= | It allows us to compute the remainder when the left operand is divided by the right operand and assign the result number to the left operand. |
C# Assignment Operators Example:
Let's consider a scenario to demonstrate the assignment operator in C#.
Example
using System;
class Program
{
static void Main() //main function
{
int a = 10, b = 6; //initializing variables and values
Console.WriteLine("The value of a is " + (a)); //using Assignment Operator
Console.WriteLine("The value of a+=b is " + (a += b)); //using Add and Assignment Operator
Console.WriteLine("The value of a-=b is " + (a -= b)); //using Subtract and Assignment Operator
Console.WriteLine("The value of a*=b is " + (a *= b)); //using Multiply and Assignment Operator
Console.WriteLine("The value of a/=b is " + (a /= b)); //using Divide and Assignment Operator
Console.WriteLine("The value of a%=b is " + (a %= b)); //using Modulus and Assignment Operator
}
}
Output:
The value of a is 10
The value of a+=b is 16
The value of a-=b is 10
The value of a*=b is 60
The value of a/=b is 10
The value of a%=b is 4
6. Unary Operators
In C#, unary operators carry out operations on a single operand.
| Operator Name | Symbol | Description |
|---|---|---|
| Unary Plus | + | It represents a positive value. It is usually optional because numbers are positive by default. |
| Unary Minus | - | It neglects the value of a variable, which transform a positive number to a negative and vice versa. |
| Increment | ++ | It increases the value of a variable by 1Prefix (++x):It increments the value first, and then it is utilized in the program.Postfix (x++):It uses the value first and then increments it. |
| Decrement | -- | It decreases the value of a variable by 1Prefix (--x):It decreases the value first, and then it is utilized in the program.Postfix (x--):It uses the value first and then decreases it. |
C# Unary Operators Example:
Let's consider an example to demonstrate the unary operator in C#.
Example
using System;
class Unary
{
static void Main() //main method
{
int a = 10; //initialize variable and value
Console.WriteLine("The value of +a is " + (+a)); // Unary plus
Console.WriteLine("The value of -a is " + (-a)); // Unary minus
Console.WriteLine("The value of a after a++ is " + (a++)); // Increment
Console.WriteLine("The value of a after a-- is " + (--a)); // Decrement
}
}
Output:
The value of +a is 10
The value of -a is -10
The value of a after a++ is 10
The value of a after a-- is 10
7. Ternary or Conditional Operator
In C#, the ternary operator serves as a substitute for if-else statements, providing a way to carry out operations on three operands. This operator functions based on conditions.
Syntax:
It has the following syntax:
(Condition) ? Expression_a : Expression_b;
Here, two scenarios arise:
- When the specified condition evaluates to true, Expression_a is triggered to deliver the corresponding outcome.
- In the case where the specified condition is false, Expression_b is activated to yield the suitable result.
C# Ternary or Conditional Operator Example:
Let's consider a scenario to demonstrate the ternary and conditional operator in C#.
Example
using System;
class Ternary
{
static void Main() //main method
{
int a = 15, b = 20;
int min = (a < b) ? a : b; // If a < b, min = a, otherwise min = b
Console.WriteLine("The minimum value is " + min);
}
}
Output:
The minimum value is 15
8. Null Coalescing Operators
In C#, null coalescing operators offer a default value in situations involving null values.
| Operator Name | Symbol | Description |
|---|---|---|
| Null Coalescing | ?? | It checks whether or not the left side operand is null. It returns the left operand if it is not null. If it is null, it returns the right operand. It enables us to provide default values. |
| Null Coalescing Assignment | ??= | It sets the left operand to the right operand only if the left operand is null. |
Null Coalescing
Null Coalescing Assignment
C# Null Coalescing Operators Example:
Let's consider a scenario to explain the null-coalescing operator in C# programming.
Example
using System;
class Program {
static void Main() {
int? num = null;
int result = num ?? 100; // If num is null, assign 100
Console.WriteLine("The result is " + result);
int? x = null;
x ??= 50; // Assigns 50 to x if it is null
Console.WriteLine("The value of x is " + x);
}
}
Output:
The result is 100
The value of x is 50
9. Operator Associativity and Precedence
In C#, operator precedence establishes the sequence in which various operators in an expression are evaluated. It dictates the priority of evaluation for diverse operators, whereas associativity specifies the sequence between operators of identical precedence, indicating whether to evaluate from the left or right.
1. Operator Precedence
Operators of greater precedence are computed before those of lower precedence. For instance, within the given expression:
Example
int result = 10 + 5 * 2;
Console.WriteLine(result);
Output:
In this case, the operation of multiplication (*) takes precedence over addition (+). Therefore, the calculation first involves multiplying 5 by 2, followed by adding 10.
2. Operator Associativity
If operators share the same precedence level, their associativity dictates the order of evaluation:
- In the case of Left-to-Right Associativity, operators such as +, -, *, /, %, &&, ||, ==, among others, are computed from left to right.
- On the other hand, Right-to-Left Associativity applies to operators like = (assignment), +=, -=, ??=, and the ternary operator (?:), which are assessed from right to left.
Example of Operator Precedence and Associativity
Example
int result = 10 - 2 * 3 + 4;
Console.WriteLine(result);
Output:
Given that the asterisk symbol (*) holds a higher priority than the minus (-) and plus (+) symbols, it undergoes evaluation before them.
Example of Right-to-Left Associativity
Example
int a = 5;
int b = 10;
int result = a = b = 20; // Right to Left evaluation
Console.WriteLine(result);
Output:
Firstly, the value of b = 20 is calculated, followed by setting a = 20, and ultimately assigning 20 to the variable result.
C# Operators Multiple Choice Questions (MCQs)
- What is the expected result of the given C# code snippet?
int a = 5, b = 10, c;
c = a++ + --b;
Console.WriteLine(c);
(B) 15
- What is the expected result produced by this specific C# code snippet?
int a = 10;
int b = 20;
int c = 30;
bool result = (a < b) && (b > c) || (a < c);
Console.WriteLine(result);
- True
- False
- Compilation Error
- Runtime Error
(A) Correct
- What is the result generated by the code snippet below?
int? x = null;
int y = x ?? 50;
Console.WriteLine(y);
- null
- Compilation Error
- Which of the following statements is correct about the ??= operator in C#?
- It assigns the right operand to the left operand only if the left operand is null.
- It always assigns the right operand to the left operand.
- It checks if two operands are equal.
- It throws an exception if the left operand is null.
- What is the result of the bitwise operation shown below?
int x = 5 & 3;
Console.WriteLine(x);