C# - Operators and Expressions

C# - Operators and Expressions

C# Operators and Expressions

In C#, operators and expressions are core building blocks of logic and computation. Operators are symbols that perform operations on variables and values, while expressions are combinations of variables, values, operators, and method calls that produce a result. This guide provides a complete reference on C# operators with examples, descriptions, and best practices.

What Are Operators in C#?

An operator in C# is a special symbol or keyword used to perform operations like addition, subtraction, comparison, logical evaluation, and more. Operators act on operands to form expressions.

Categories of Operators in C#

C# provides a wide range of operators categorized as follows:

  • Arithmetic Operators
  • Relational (Comparison) Operators
  • Logical Operators
  • Assignment Operators
  • Unary Operators
  • Bitwise Operators
  • Conditional (Ternary) Operator
  • Null-Coalescing Operators
  • Type Check and Cast Operators
  • Miscellaneous Operators

1. Arithmetic Operators

Arithmetic operators are used for basic mathematical operations.

Operator Description Example
+Additiona + b
-Subtractiona - b
*Multiplicationa * b
/Divisiona / b
%Modulus (remainder)a % b
int a = 10;
int b = 3;

Console.WriteLine(a + b); // 13
Console.WriteLine(a - b); // 7
Console.WriteLine(a * b); // 30
Console.WriteLine(a / b); // 3
Console.WriteLine(a % b); // 1

2. Relational (Comparison) Operators

Used to compare two values. The result is a boolean (true or false).

OperatorDescriptionExample
==Equal toa == b
!=Not equal toa != b
>Greater thana > b
<Less thana < b
>=Greater than or equal toa >= b
<=Less than or equal toa <= b
int x = 7, y = 5;

Console.WriteLine(x == y); // False
Console.WriteLine(x != y); // True
Console.WriteLine(x > y);  // True
Console.WriteLine(x < y);  // False
Console.WriteLine(x >= y); // True
Console.WriteLine(x <= y); // False

3. Logical Operators

Used to combine multiple boolean expressions.

OperatorDescriptionExample
&&Logical ANDa && b
||Logical ORa || b
!Logical NOT!a
bool a = true, b = false;

Console.WriteLine(a && b); // False
Console.WriteLine(a || b); // True
Console.WriteLine(!a);     // False

4. Assignment Operators

Used to assign values to variables.

OperatorDescriptionExample
=Assigna = 10
+=Add and assigna += 5
-=Subtract and assigna -= 2
*=Multiply and assigna *= 3
/=Divide and assigna /= 4
%=Modulus and assigna %= 2
int a = 10;
a += 5; // a = 15
a *= 2; // a = 30
a /= 3; // a = 10

5. Unary Operators

Operators that act on a single operand.

int x = 5;
Console.WriteLine(+x);  // 5
Console.WriteLine(-x);  // -5
Console.WriteLine(++x); // 6
Console.WriteLine(--x); // 5
Console.WriteLine(x++); // 5 (then x becomes 6)
Console.WriteLine(x--); // 6 (then x becomes 5)

6. Bitwise Operators

Used to manipulate individual bits.

OperatorDescriptionExample
&ANDa & b
|ORa | b
^XORa ^ b
~Complement~a
<<Left shifta << 1
>>Right shifta >> 1
int a = 5;    // 0101
int b = 3;    // 0011

Console.WriteLine(a & b);  // 0001 -> 1
Console.WriteLine(a | b);  // 0111 -> 7
Console.WriteLine(a ^ b);  // 0110 -> 6
Console.WriteLine(~a);     // Complement
Console.WriteLine(a << 1); // 1010 -> 10
Console.WriteLine(a >> 1); // 0010 -> 2

7. Conditional (Ternary) Operator

Shorthand for if-else.

int age = 18;
string result = (age >= 18) ? "Adult" : "Minor";
Console.WriteLine(result); // Adult

8. Null-Coalescing Operators

?? Operator

Returns the left operand if it’s not null, otherwise returns the right operand.

string name = null;
string finalName = name ?? "Default Name";
Console.WriteLine(finalName); // Default Name

??= Operator

Assigns value to a variable only if it is null.

string message = null;
message ??= "Hello!";
Console.WriteLine(message); // Hello!

9. Type Check and Cast Operators

is Operator

object obj = "Hello";
if (obj is string)
{
    Console.WriteLine("It is a string.");
}

as Operator

object data = "World";
string text = data as string;
Console.WriteLine(text); // World

10. Operator Precedence and Associativity

C# evaluates operators in a specific order (precedence). Parentheses can change this behavior.

int result = 10 + 5 * 2;       // result = 20
int changed = (10 + 5) * 2;   // changed = 30

Expressions in C#

An expression is a combination of literals, variables, operators, and method calls that result in a value.

int a = 5, b = 10;
int sum = a + b;           // Arithmetic expression
bool isGreater = a < b;     // Boolean expression
string fullName = "John" + " " + "Doe"; // String expression

C# offers a rich set of operators that allow you to perform various operations efficiently. From arithmetic and comparison to bitwise and logical evaluations, mastering operators and expressions is essential for any C# programmer. With clear understanding and proper usage, you can write clean, readable, and performant code. As you work on real-world applications, combining multiple operators in expressions becomes a daily necessity. Keep practicing with different examples to reinforce your learning of this foundational topic in C# development.

Beginner 5 Hours
C# - Operators and Expressions

C# Operators and Expressions

In C#, operators and expressions are core building blocks of logic and computation. Operators are symbols that perform operations on variables and values, while expressions are combinations of variables, values, operators, and method calls that produce a result. This guide provides a complete reference on C# operators with examples, descriptions, and best practices.

What Are Operators in C#?

An operator in C# is a special symbol or keyword used to perform operations like addition, subtraction, comparison, logical evaluation, and more. Operators act on operands to form expressions.

Categories of Operators in C#

C# provides a wide range of operators categorized as follows:

  • Arithmetic Operators
  • Relational (Comparison) Operators
  • Logical Operators
  • Assignment Operators
  • Unary Operators
  • Bitwise Operators
  • Conditional (Ternary) Operator
  • Null-Coalescing Operators
  • Type Check and Cast Operators
  • Miscellaneous Operators

1. Arithmetic Operators

Arithmetic operators are used for basic mathematical operations.

Operator Description Example
+Additiona + b
-Subtractiona - b
*Multiplicationa * b
/Divisiona / b
%Modulus (remainder)a % b
int a = 10; int b = 3; Console.WriteLine(a + b); // 13 Console.WriteLine(a - b); // 7 Console.WriteLine(a * b); // 30 Console.WriteLine(a / b); // 3 Console.WriteLine(a % b); // 1

2. Relational (Comparison) Operators

Used to compare two values. The result is a boolean (true or false).

OperatorDescriptionExample
==Equal toa == b
!=Not equal toa != b
>Greater thana > b
<Less thana < b
>=Greater than or equal toa >= b
<=Less than or equal toa <= b
int x = 7, y = 5; Console.WriteLine(x == y); // False Console.WriteLine(x != y); // True Console.WriteLine(x > y); // True Console.WriteLine(x < y); // False Console.WriteLine(x >= y); // True Console.WriteLine(x <= y); // False

3. Logical Operators

Used to combine multiple boolean expressions.

OperatorDescriptionExample
&&Logical ANDa && b
||Logical ORa || b
!Logical NOT!a
bool a = true, b = false; Console.WriteLine(a && b); // False Console.WriteLine(a || b); // True Console.WriteLine(!a); // False

4. Assignment Operators

Used to assign values to variables.

OperatorDescriptionExample
=Assigna = 10
+=Add and assigna += 5
-=Subtract and assigna -= 2
*=Multiply and assigna *= 3
/=Divide and assigna /= 4
%=Modulus and assigna %= 2
int a = 10; a += 5; // a = 15 a *= 2; // a = 30 a /= 3; // a = 10

5. Unary Operators

Operators that act on a single operand.

int x = 5; Console.WriteLine(+x); // 5 Console.WriteLine(-x); // -5 Console.WriteLine(++x); // 6 Console.WriteLine(--x); // 5 Console.WriteLine(x++); // 5 (then x becomes 6) Console.WriteLine(x--); // 6 (then x becomes 5)

6. Bitwise Operators

Used to manipulate individual bits.

OperatorDescriptionExample
&ANDa & b
|ORa | b
^XORa ^ b
~Complement~a
<<Left shifta << 1
>>Right shifta >> 1
int a = 5; // 0101 int b = 3; // 0011 Console.WriteLine(a & b); // 0001 -> 1 Console.WriteLine(a | b); // 0111 -> 7 Console.WriteLine(a ^ b); // 0110 -> 6 Console.WriteLine(~a); // Complement Console.WriteLine(a << 1); // 1010 -> 10 Console.WriteLine(a >> 1); // 0010 -> 2

7. Conditional (Ternary) Operator

Shorthand for if-else.

int age = 18; string result = (age >= 18) ? "Adult" : "Minor"; Console.WriteLine(result); // Adult

8. Null-Coalescing Operators

?? Operator

Returns the left operand if it’s not null, otherwise returns the right operand.

string name = null; string finalName = name ?? "Default Name"; Console.WriteLine(finalName); // Default Name

??= Operator

Assigns value to a variable only if it is null.

string message = null; message ??= "Hello!"; Console.WriteLine(message); // Hello!

9. Type Check and Cast Operators

is Operator

object obj = "Hello"; if (obj is string) { Console.WriteLine("It is a string."); }

as Operator

object data = "World"; string text = data as string; Console.WriteLine(text); // World

10. Operator Precedence and Associativity

C# evaluates operators in a specific order (precedence). Parentheses can change this behavior.

int result = 10 + 5 * 2; // result = 20 int changed = (10 + 5) * 2; // changed = 30

Expressions in C#

An expression is a combination of literals, variables, operators, and method calls that result in a value.

int a = 5, b = 10; int sum = a + b; // Arithmetic expression bool isGreater = a < b; // Boolean expression string fullName = "John" + " " + "Doe"; // String expression

C# offers a rich set of operators that allow you to perform various operations efficiently. From arithmetic and comparison to bitwise and logical evaluations, mastering operators and expressions is essential for any C# programmer. With clear understanding and proper usage, you can write clean, readable, and performant code. As you work on real-world applications, combining multiple operators in expressions becomes a daily necessity. Keep practicing with different examples to reinforce your learning of this foundational topic in C# development.

Related Tutorials

Frequently Asked Questions for General

line

Copyrights © 2024 letsupdateskills All rights reserved