C# Tutorial
Estimated reading: 4 minutes 32 views

4️⃣ C# Operators – Complete Guide to Expressions, Logic & Overloading

C# operators form the foundation for expressions and computations. From simple math to complex logic and custom class behavior, operators enable developers to write expressive and readable code.


🪂 Introduction – Why Learn C# Operators?

Operators in C# let you manipulate data, compare values, evaluate conditions, and even define custom behavior for your own classes. Whether you’re calculating totals, validating input, or creating powerful expressions, understanding C# operators is key to writing clean and functional code.

🌟 In this guide, you’ll explore:

  • Core categories of operators in C#
  • How precedence affects expression evaluation
  • How to redefine operator behavior for custom types

📃 Topics Covered

SubtopicDescription
➕ C# Operators OverviewIntroduction to operator types and usage
➕ C# Arithmetic OperatorsPerform basic math calculations
➕ C# Assignment OperatorsAssign and update variable values
➕ C# Relational OperatorsCompare values for conditional logic
➕ C# Logical OperatorsCombine boolean expressions
➕ C# Bitwise OperatorsOperate at the binary level
➕ C# Miscellaneous OperatorsSpecialized operators like ternary, null-coalescing, etc.
➕ C# Operator PrecedenceUnderstand expression evaluation order
➕ C# Operator OverloadingCustomize operators for user-defined types

➕ C# Operators Overview

Operators in C# are used to perform operations on variables, constants, and expressions. They include categories such as arithmetic, logical, relational, and assignment operators.

int a = 10, b = 5;
int sum = a + b; // Using arithmetic and assignment operators

➕ C# Arithmetic Operators

These operators are used to perform mathematical calculations:

OperatorDescriptionExampleResult
+Additiona + b15
-Subtractiona - b5
*Multiplicationa * b50
/Divisiona / b2
%Modulusa % b0

➕ C# Assignment Operators

These operators assign values and can combine with arithmetic:

OperatorMeaningExampleEquivalent
=Assigna = 5Assign 5 to a
+=Add & assigna += 2a = a + 2
-=Subtract & assigna -= 2a = a - 2
*=Multiply & assigna *= 2a = a * 2
/=Divide & assigna /= 2a = a / 2

➕ C# Relational Operators

Used to compare values:

OperatorDescriptionExampleResult
==Equal toa == bfalse
!=Not equal toa != btrue
>Greater thana > btrue
<Less thana < bfalse
>=Greater or equala >= btrue
<=Less or equala <= bfalse

➕ C# Logical Operators

Used to combine boolean expressions:

OperatorDescriptionExampleResult
&&Logical ANDtrue && falsefalse
``Logical OR`truefalse`true
!Logical NOT!truefalse

➕ C# Bitwise Operators

Operate at the bit level:

OperatorDescriptionExampleResult
&AND5 & 31
``OR`53`7
^XOR5 ^ 36
~NOT~5-6
<<Left shift5 << 110
>>Right shift5 >> 12

➕ C# Miscellaneous Operators

OperatorPurposeExample
?:Ternary conditionala > b ? a : b
??Null coalescingname ?? "Guest"
?.Null-conditional accessobj?.ToString()
typeofGet type at runtimetypeof(int)
isType checkingobj is string
asSafe castingobj as string
nameofReturn name of variable as stringnameof(variable)

➕ C# Operator Precedence

Operators are evaluated in a specific order. For example, multiplication and division have higher precedence than addition and subtraction. Use parentheses to control precedence explicitly.

int result = 10 + 2 * 5;       // Result: 20
int adjusted = (10 + 2) * 5;   // Result: 60

➕ C# Operator Overloading

C# allows overloading operators in user-defined types to make code more intuitive.

public class Point
{
    public int X, Y;

    public static Point operator +(Point a, Point b)
    {
        return new Point { X = a.X + b.X, Y = a.Y + b.Y };
    }
}

This enables:

Point p1 = new Point { X = 1, Y = 2 };
Point p2 = new Point { X = 3, Y = 4 };
Point sum = p1 + p2;

📌 Summary – Recap & Next Steps

Understanding operators in C# enables you to write concise, expressive, and optimized code. From basic arithmetic to overloading custom behaviors, operators are the building blocks of logical computation.

🔍 Key Takeaways:

  • Operators are categorized as arithmetic, assignment, logical, and more
  • Operator precedence affects evaluation order
  • You can customize operator behavior for classes via overloading

️️ Real-World Relevance: Operators simplify conditionals, loops, math, and object manipulation in virtually every application.


❓ FAQs

Q: Can all operators be overloaded in C#? ✅ No. You can overload most arithmetic and comparison operators, but not logical operators like &&, ||, or =.

Q: What is the difference between ** and ** in C#?== can be overloaded for custom behavior, while Equals() checks object equality by default and can be overridden.

Q: Is the null-coalescing operator “ the same as a ternary? ✅ No. ?? only checks for null and returns a default, while ?: is a general-purpose condition.

Q: How do I avoid ambiguity in complex expressions? ✅ Use parentheses to control operator precedence and clarify evaluation order.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

4️⃣ C# Operators

Or Copy Link

CONTENTS
Scroll to Top