Additional Operators

Exploring additional operators in C#.

* 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:

int? nullableValue = null;
int result = nullableValue ?? 10;
// 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:

Person person = null;
string personName = person?.Name;
/*personName will be null instead of
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:

int? nullableValue = null;
nullableValue ??= 10;
// 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:

Func<int, int, int> add = (a, b) => a + b;
int result = add(5, 7);
// 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:

int[] numbers = { 1, 2, 3, 4, 5 };
int thirdElement = numbers[2];
// 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:

int[] numbers = { 1, 2, 3, 4, 5 };
int[] subArray = numbers[1..4];
// 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 actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.