C# -

Operators

Operators are special symbols that perform operations on operands (variables and values). C# supports a wide range of operators to perform various operations, including arithmetic, logical, relational, bitwise, assignment, and more. Understanding these operators is crucial for effective programming in C#.


1. Arithmetic Operators

Arithmetic operators perform mathematical calculations.

Operator Description Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulus (remainder) a % b
++ Increment (by 1) a++ or ++a
-- Decrement (by 1) a-- or --a
Basic Example:
        
            using System;

namespace ArithmeticOperators

class Program
{
    static void Main(string[] args)
    {
        int a = 10;
        int b = 5;

        int sum = a + b;
        int difference = a - b;
        int product = a * b;
        int quotient = a / b;
        int remainder = a % b;

        Console.WriteLine($"Sum: {sum}");
        Console.WriteLine($"Difference: {difference}");
        Console.WriteLine($"Product: {product}");
        Console.WriteLine($"Quotient: {quotient}");
        Console.WriteLine($"Remainder: {remainder}");
    }
}

        
    
Advanced Example:
        
            using System;

namespace ArithmeticOperators

class Program
{
    static void Main(string[] args)
    {
        int a = 10;
        int b = 5;
        int c = 3;

        // Combined arithmetic operations
        int result = a + b * c - (a / c) + (b % c);

        Console.WriteLine($"Result: {result}");

        // Increment and decrement operations
        int x = 10;
        Console.WriteLine($"Initial x: {x}");
        Console.WriteLine($"x++: {x++}");
        Console.WriteLine($"++x: {++x}");
        Console.WriteLine($"x--: {x--}");
        Console.WriteLine($"--x: {--x}");
    }
}

        
    

2. Relational Operators

Relational operators compare two values and return a boolean result (true or false).

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
Basic Example:
        
            using System;

namespace RelationalOperators

class Program
{
    static void Main(string[] args)
    {
        int a = 10;
        int b = 5;

        bool isEqual = a == b;
        bool isNotEqual = a != b;
        bool isGreaterThan = a > b;
        bool isLessThan = a < b;
        bool isGreaterThanOrEqual = a >= b;
        bool isLessThanOrEqual = a <= b;

        Console.WriteLine($"a == b: {isEqual}");
        Console.WriteLine($"a != b: {isNotEqual}");
        Console.WriteLine($"a > b: {isGreaterThan}");
        Console.WriteLine($"a < b: {isLessThan}");
        Console.WriteLine($"a >= b: {isGreaterThanOrEqual}");
        Console.WriteLine($"a <= b: {isLessThanOrEqual}");
    }
}

        
    
Advanced Example:
        
            using System;

namespace RelationalOperators

class Program
{
    static void Main(string[] args)
    {
        int a = 10;
        int b = 5;
        int c = 10;

        // Combining relational operations with logical operators
        bool result1 = (a > b) && (a == c);
        bool result2 = (a < b) || (b <= c);
        bool result3 = !(a != c);

        Console.WriteLine($"(a > b) && (a == c): {result1}");
        Console.WriteLine($"(a < b) || (b <= c): {result2}");
        Console.WriteLine($"!(a != c): {result3}");
    }
}

        
    

3. Logical Operators

Logical operators perform logical operations on boolean values and return a boolean result.

Operator Description Example
&& Logical AND a && b
|| Logical OR a || b
! Logical NOT !a
Basic Example:
        
            using System;

namespace LogicalOperators

class Program
{
    static void Main(string[] args)
    {
        bool a = true;
        bool b = false;

        bool andResult = a && b;
        bool orResult = a || b;
        bool notResult = !a;

        Console.WriteLine($"a && b: {andResult}");
        Console.WriteLine($"a || b: {orResult}");
        Console.WriteLine($"!a: {notResult}");
    }
}

        
    
Advanced Example:
        
            using System;

namespace LogicalOperators

class Program
{
    static void Main(string[] args)
    {
        bool a = true;
        bool b = false;
        bool c = true;

        // Combining logical operators with relational operators
        bool result1 = (a && b) || c;
        bool result2 = !(a && (b || c));

        Console.WriteLine($"(a && b) || c: {result1}");
        Console.WriteLine($"!(a && (b || c)): {result2}");
    }
}

        
    

4. Bitwise Operators

Bitwise operators perform bit-level operations on integer types.

Operator Description Example
& Bitwise AND a & b
| Bitwise OR a | b
^ Bitwise XOR a ^ b
~ Bitwise NOT ~a
<< Left shift a << b
>> Right shift a >> b
Basic Example:
        
            using System;

namespace BitwiseOperators

class Program
{
    static void Main(string[] args)
    {
        int a = 5;  // 0101 in binary
        int b = 3;  // 0011 in binary

        int andResult = a & b; // 0001 in binary
        int orResult = a | b;  // 0111 in binary
        int xorResult = a ^ b; // 0110 in binary
        int notResult = ~a;    // 1111...1010 in binary (two's complement representation)
        int leftShiftResult = a << 1; // 1010 in binary
        int rightShiftResult = a >> 1; // 0010 in binary

        Console.WriteLine($"a & b: {andResult}");
        Console.WriteLine($"a | b: {orResult}");
        Console.WriteLine($"a ^ b: {xorResult}");
        Console.WriteLine($"~a: {notResult}");
        Console.WriteLine($"a << 1: {leftShiftResult}");
        Console.WriteLine($"a >> 1: {rightShiftResult}");
    }
}

        
    
Advanced Example:
        
            using System;

namespace BitwiseOperators

class Program
{
    static void Main(string[] args)
    {
        int a = 12;  // 1100 in binary
        int b = 25;  // 11001 in binary

        // Combining bitwise operators with arithmetic operations
        int result1 = (a & b) + (a | b);
        int result2 = (a ^ b) - (~b);
        int result3 = (a << 2) + (b >> 2);

        Console.WriteLine($"(a & b) + (a | b): {result1}");
        Console.WriteLine($"(a ^ b) - (~b): {result2}");
        Console.WriteLine($"(a << 2) + (b >> 2): {result3}");
    }
}

        
    

5. Assignment Operators

Assignment operators assign values to variables.

Operator Description Example
= Assign a = b
+= Add and assign a += b
-= Subtract and assign a -= b
*= Multiply and assign a *= b
/= Divide and assign a /= b
%= Modulus and assign a %= b
&= Bitwise AND and assign a &= b
|= Bitwise OR and assign a |= b
^= Bitwise XOR and assign a ^= b
<<= Left shift and assign a <<= b
>>= Right shift and assign a >>= b
Basic Example:
        
            using System;

namespace AssignmentOperators

class Program
{
    static void Main(string[] args)
    {
        int a = 10;
        int b = 5;

        a += b; // a = a + b
        Console.WriteLine($"a += b: {a}");

        a -= b; // a = a - b
        Console.WriteLine($"a -= b: {a}");

        a *= b; // a = a * b
        Console.WriteLine($"a *= b: {a}");

        a /= b; // a = a / b
        Console.WriteLine($"a /= b: {a}");

        a %= b; // a = a % b
        Console.WriteLine($"a %= b: {a}");
    }
}

        
    
Advanced Example:
        
            using System;

namespace AssignmentOperators

class Program
{
    static void Main(string[] args)
    {
        int a = 10;
        int b = 5;
        int c = 3;

        a += b * c; // a = a + (b * c)
        Console.WriteLine($"a += b * c: {a}");

        a -= b / c; // a = a - (b / c)
        Console.WriteLine($"a -= b / c: {a}");

        a *= b % c; // a = a * (b % c)
        Console.WriteLine($"a *= b % c: {a}");

        a /= b + c; // a = a / (b + c)
        Console.WriteLine($"a /= b + c: {a}");

        a %= b - c; // a = a % (b - c)
        Console.WriteLine($"a %= b - c: {a}");
    }
}

        
    

6. Conditional Operator

The conditional operator `? :` is a ternary operator that returns one of two values depending on the value of a Boolean expression.

Operator Description Example
? : Conditional condition ? value_if_true : value_if_false
Basic Example:
        
            using System;

namespace ConditionalOperator

class Program
{
    static void Main(string[] args)
    {
        int a = 10;
        int b = 20;

        // Basic usage of conditional operator
        string result = (a > b) ? "a is greater than b" : "a is less than or equal to b";
        Console.WriteLine(result);
    }
}

        
    
Advanced Example:
        
            using System;

namespace ConditionalOperator

class Program
{
    static void Main(string[] args)
    {
        int a = 10;
        int b = 20;
        int c = 5;

        // Nested conditional operators
        string result = (a > b) ? "a is greater than b" :
                        (b > c) ? "b is greater than c" :
                        "c is the greatest";

        Console.WriteLine(result);
    }
}

        
    

7. Null-Coalescing Operators

Null-coalescing operators provide a convenient way to handle null values.

Operator Description Example
?? Null-coalescing a ?? b
??= Null-coalescing assignment a ??= b
Basic Example:
        
            using System;

namespace NullCoalescingOperators

class Program
{
    static void Main(string[] args)
    {
        string name = null;
        string defaultName = "Default";

        // Using null-coalescing operator
        string finalName = name ?? defaultName;
        Console.WriteLine($"Name: {finalName}");
    }
}

        
    
Advanced Example:
        
            using System;

namespace NullCoalescingOperators

class Program
{
    static void Main(string[] args)
    {
        string[] names = { null, "John", "Doe" };
        string defaultName = "Default";

        foreach (var name in names)
        {
            // Using null-coalescing assignment operator
            string finalName = name ??= defaultName;
            Console.WriteLine($"Name: {finalName}");
        }
    }
}

        
    

8. Miscellaneous Operators

C# provides several other operators for specific purposes.

Operator Description Example
`is` Type compatibility a is Type
`as` Type conversion a as Type
`sizeof` Returns the size of a type sizeof(Type)
`typeof` Returns the System.Type object for a type typeof(Type)
`nameof` Returns the name of a variable, type, or member as a string nameof(variable)
`checked` Checks for arithmetic overflow checked(expression)
`unchecked` Suppresses overflow-checking unchecked(expression)
`default` Returns the default value of a type default(Type)
Basic Example:
        
            using System;

namespace MiscellaneousOperators

class Program
{
    static void Main(string[] args)
    {
        int a = 10;
        Type type = typeof(int);
        bool isInt = a is int;

        Console.WriteLine($"Type of a: {type}");
        Console.WriteLine($"a is int: {isInt}");
    }
}

        
    
Advanced Example:
        
            using System;

namespace MiscellaneousOperators

class Program
{
    static void Main(string[] args)
    {
        object obj = "Hello, world!";
        string str = obj as string;

        Console.WriteLine($"String: {str}");

        // Using nameof and default operators
        Console.WriteLine($"Name of variable: {nameof(obj)}");
        int defaultValue = default(int);
        Console.WriteLine($"Default value of int: {defaultValue}");
    }
}

        
    

9. Operator Overloading

C# allows you to define custom behavior for operators in your own classes or structs.

Example:
        
            using System;

namespace OperatorOverloading

class Complex
{
    public int Real { get; set; }
    public int Imaginary { get; set; }

    public Complex(int real, int imaginary)
    {
        Real = real;
        Imaginary = imaginary;
    }

    // Overloading the + operator
    public static Complex operator +(Complex c1, Complex c2)
    {
        return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
    }

    public override string ToString()
    {
        return $"{Real} + {Imaginary}i";
    }
}

class Program
{
    static void Main(string[] args)
    {
        Complex c1 = new Complex(1, 2);
        Complex c2 = new Complex(3, 4);
        Complex result = c1 + c2;

        Console.WriteLine($"Result: {result}");
    }
}

        
    

10. Best Practices


11. Conclusion

Understanding and applying operators correctly is crucial for writing efficient and effective C# code. This tutorial covered various types of operators with examples to help you grasp their usage and best practices.