DEV Community

Adrián Bailador
Adrián Bailador

Posted on

13 1 1

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

Billboard image

Monitor more than uptime.

With Checkly, you can use Playwright tests and Javascript to monitor end-to-end scenarios in your NextJS, Astro, Remix, or other application.

Get started now!

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay