DEV Community

Adrián Bailador
Adrián Bailador

Posted on

20 Shorthand Operators in C#

This article explores 20 essential shorthand operators every C# developer should master, complete with examples to understand their practical use.

1. Conditional Operator ? :

Also known as the ternary operator, it evaluates a condition and returns one of two values based on the result.

int age = 18;
string status = age >= 18 ? "Adult" : "Minor";
Console.WriteLine(status); 
Enter fullscreen mode Exit fullscreen mode

2. Null-Conditional Operator (Member Access) ?.

Safely access members of an object that might be null without throwing a NullReferenceException.

string? name = null;
int? length = name?.Length;
Console.WriteLine(length); 
Enter fullscreen mode Exit fullscreen mode

3. Null-Conditional Operator (Element Access) ?[]

Similar to ?. but used for arrays or collections.

int[]? numbers = null;
int? firstNumber = numbers?[0];
Console.WriteLine(firstNumber); 
Enter fullscreen mode Exit fullscreen mode

4. Null-Coalescing Operator ??

Provides a default value if the left-hand operand is null.

string? name = null;
string displayName = name ?? "Guest";
Console.WriteLine(displayName); 
Enter fullscreen mode Exit fullscreen mode

5. Null-Coalescing Assignment Operator ??=

Assigns a value to a variable only if it is null.

string? name = null;
name ??= "Default Name";
Console.WriteLine(name); 
Enter fullscreen mode Exit fullscreen mode

6. Null-Forgiving Operator !

Tells the compiler that a value will not be null, bypassing nullability warnings (use cautiously).

string? name = null;
int length = name!.Length;
Enter fullscreen mode Exit fullscreen mode

7. Index Operator ^

Access elements from the end of a collection.

int[] numbers = { 1, 2, 3, 4, 5 };
int last = numbers[^1];
Console.WriteLine(last); 
Enter fullscreen mode Exit fullscreen mode

8. Range Operator ..

Creates a range of elements from a collection.

int[] numbers = { 1, 2, 3, 4, 5 };
int[] subset = numbers[1..4];
Console.WriteLine(string.Join(", ", subset)); 
Enter fullscreen mode Exit fullscreen mode

9. Expression Body Definition =>

Simplifies method or property definitions.

public class Calculator
{
    public int Add(int a, int b) => a + b;
}

Calculator calc = new Calculator();
Console.WriteLine(calc.Add(3, 5));
Enter fullscreen mode Exit fullscreen mode

10. Type-Testing Operator is

Checks if an object is of a specific type.

object obj = "Codú";
if (obj is string text)
{
    Console.WriteLine(text);
}
Enter fullscreen mode Exit fullscreen mode

11. Type-Testing Negation Operator is not

Ensures an object is not of a specific type.

object obj = 42;
if (obj is not string)
{
    Console.WriteLine("Not a string");
}
Enter fullscreen mode Exit fullscreen mode

12. Type-Casting Operator as

Attempts to cast an object to a specific type, returning null if unsuccessful.

object obj = "Codú";
string? text = obj as string;
Console.WriteLine(text); 
Enter fullscreen mode Exit fullscreen mode

13. Compound Assignment Operators (e.g., +=, -=)

Combines an operation with assignment.

int x = 5;
x += 3; // Equivalent to x = x + 3
Console.WriteLine(x); 
Enter fullscreen mode Exit fullscreen mode

14. Lambda Operator => in LINQ

Defines inline functions for LINQ queries.

int[] numbers = { 1, 2, 3, 4, 5 };
var evens = numbers.Where(n => n % 2 == 0);
Console.WriteLine(string.Join(", ", evens)); 
Enter fullscreen mode Exit fullscreen mode

15. Elvis Operator in String Interpolation $"{expr}"

Safely handles null values in interpolated strings.

string? name = null;
Console.WriteLine($"Hello, {name ?? "Codú"}!"); 
Enter fullscreen mode Exit fullscreen mode

16. Default Literal default

Initializes a variable with its default value for the given type.

int number = default;
Console.WriteLine(number); 
Enter fullscreen mode Exit fullscreen mode

17. Discard Operator _

Ignores values you do not need.

(int a, _) = (1, 2);
Console.WriteLine(a); 
Enter fullscreen mode Exit fullscreen mode

18. Interpolated Verbatim Strings $@

Combines interpolated and verbatim strings.

string path = "C:\\Users\\{Environment.UserName}";
Console.WriteLine($@"Path: {path}"); 
Enter fullscreen mode Exit fullscreen mode

19. Conditional Access with Indexer ?[index]

Combines safe navigation and index access.

Dictionary<string, int>? scores = null;
int? value = scores?["Codu"];
Console.WriteLine(value); 
Enter fullscreen mode Exit fullscreen mode

20. Switch Expression switch

A concise way to return values based on conditions.

string GetDayType(int day) => day switch
{
    1 => "Monday",
    2 => "Tuesday",
    _ => "Other",
};

Console.WriteLine(GetDayType(1)); 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)