C# Language
* C# has several additional operator features beyond the basic operators, e.g., arithmetic, comparison, logical operators, etc.
Additional Operators
Null Coalescing Operator:
The null coalescing operator is used to provide a default value for a nullable type or to handle null values.
Operator: ??
Example:
1 | int? nullableValue = null; |
2 | int result = nullableValue ?? 10; |
3 | // result will be 10 if nullableValue is null |
Null Conditional Operator:
The range operator is used to create a range of values, often used with collections to specify a range of elements.
Operator: ?.
Example:
1 | Person person = null; |
2 | string personName = person?.Name; |
3 | /*personName will be null instead of |
4 | throwing a null reference exception*/ |
Coalesce Assignment Operator:
The coalesce assignment operator is used to assign the right-hand operand to the left-hand operand only if the left-hand operand is 'null'.
Operator: ??=
Example:
1 | int? nullableValue = null; |
2 | nullableValue ??= 10; |
3 | // nullableValue is assigned 10 if it is initially null |
Lambda Operator:
The lambda operator is used to create lambda expressions, which are a concise way to represent anonymous methods or delegates.
Operator: =>
Example:
1 | Func<int, int, int> add = (a, b) => a + b; |
2 | int result = add(5, 7); |
3 | // result will be 12 |
Index Operator:
The index operator is used to access elements in arrays, lists, strings, and other types that support indexing.
Operator: []
Example:
1 | int[] numbers = { 1, 2, 3, 4, 5 }; |
2 | int thirdElement = numbers[2]; |
3 | // thirdElement will be 3 |
Range Operator:
The range operator is used to create a range of values, often used with collections to specify a range of elements.
Operator: ..
Example:
1 | int[] numbers = { 1, 2, 3, 4, 5 }; |
2 | int[] subArray = numbers[1..4]; |
3 | // subArray will be { 2, 3, 4 } |
* These are just a few additional operators in C#. The language provides various operators to handle different scenarios efficiently.
What's Next?
We've now entered the finance section on this platform, where you can enhance your financial literacy.