Operators
C# expression operators are fundamental tools for performing computations and evaluating conditions in code.
- Arithmetic operators (+, -, *, /, %) allow you to perform addition, subtraction, multiplication, division, and modulo operations on numeric values.
- Comparison operators (==, !=, <, >, <=, >=) are used to compare values and determine relationships, such as equality or order.
- Logical operators (&&, ||, !) evaluate boolean expressions and help combine conditions to make decisions or control program flow.
- The conditional operator (?:) allows for concise conditional expressions, making it easier to handle branching logic based on a condition.
- Assignment operators (=, +=, -=, etc.) assign values to variables or update them by performing an operation.
- Bitwise operators (&, |, ^, <<, >>) operate on individual bits of numeric values, enabling low-level manipulation and optimization.
- The null-coalescing operator (??) concisely handles null values, allowing for fallback or default values when encountering null references.
By understanding and utilizing these operators, you gain powerful tools to perform calculations, make decisions, and control the behavior of your C# programs.
C# Lambda expression operator (=>) is a shorthand syntax for defining anonymous functions. It allows you to write compact and inline functions without the need to declare a separate method. Lambdas are commonly used in LINQ queries, event handlers, and functional programming. They improve code readability, enable concise operations on collections, and provide a flexible way to work with data and delegates.
In lambda expressions, the lambda operator =>
separates the input parameters on the left side from the lambda body on the right side.
Here's an example that calculates the square of each number in a list:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
List<int> squaredNumbers = numbers.Select(x => x * x).ToList();
// squaredNumbers will be [1, 4, 9, 16, 25]
In this code, we have a list of numbers. Using the Select
method and a Lambda expression x => x * x
, we square each number in the list. The Lambda expression takes an input x
and returns its square x * x
. Finally, we have a new list squaredNumbers
containing the squared values of the original numbers. Lambda expressions are versatile and enable concise operations on collections, making code more expressive and readable.
Comments