C# Tips & Tricks You Wish You Knew Sooner

Modern C# is full of powerful tips and tricks that can streamline your coding process, but many of these gems fly under the radar. Here are some lesser-known shortcuts and techniques that can help you level up your C# game:

c# tips and tricks

1. Pattern Matching Enhancements

C#’s pattern matching has evolved significantly. Beyond simple type checks, you can now use property patterns and positional patterns to deconstruct objects directly:

public string DescribeOrder(Order order) =>
    order switch
    {
        { IsInternational: true, Weight: > 10 } => "Heavy international order",
        { IsInternational: true } => "Light international order",
        { Weight: > 5 } => "Heavy domestic order",
        _ => "Standard order"
    };

Why It’s Cool: This reduces complex nested conditionals and makes your intent crystal clear.


2. Using Discards for Cleaner Code

Ever call a method that returns multiple out parameters but only need some of the results? Use the discard operator (_) to ignore unwanted values:

int.TryParse(input, out var number);

Or, if you don’t need the result:

int.TryParse(input, out _);

Why It’s Cool: It keeps your code tidy and avoids cluttering your namespace with unused variables.


3. Target-Typed New Expressions

Since C# 9, you can simplify object instantiation by omitting the type on the right-hand side letting the compiler infer it:

List<string> names = new() { "Alice", "Bob" };

Why It’s Cool: It makes your code less verbose and improves readability.


4. Expression-Bodied Members

Simplify methods and properties using expression-bodied syntax. This can make even more complex logic look concise:

public int Square(int number) => number * number;
public string Name { get; set; } = "Default";

Why It’s Cool: Reduces boilerplate code and highlights the method’s purpose at a glance.


5. Null-Coalescing and Null-Conditional Operators

Combine these operators for powerful, concise null checks:

var result = myObject?.Property ?? "Fallback Value";

Why It’s Cool: These operators prevent null reference exceptions with minimal syntax.


6. Local Functions & Lambda Expressions

Keep helper functions close to where they’re used. Local functions and lambda expressions can both reduce clutter and improve readability:

public void ProcessData(List<int> data)
{
    int Sum() => data.Sum();
    Console.WriteLine($"Total: {Sum()}");
}

Why It’s Cool: Encapsulating functionality within a method keeps your code modular and easier to maintain.


7. Interpolated Strings and Advanced Formatting

Modern interpolated strings in C# support advanced formatting options that were previously more cumbersome:

double price = 123.456;
Console.WriteLine($"Price: {price:C2}");  // Outputs: Price: $123.46

Why It’s Cool: It simplifies string formatting and improves clarity, especially when dealing with currency or dates.


8. Using nameof for Refactor-Safe Code

The nameof operator helps avoid magic strings in your code, making it much safer during refactoring:

public void LogError(string propertyName)
{
    Console.WriteLine($"Error in property: {propertyName}");
}

LogError(nameof(MyProperty));

Why It’s Cool: It reduces runtime errors due to typos and makes your code more resilient to changes.


Why These C# Tips and Tricks Matter

These advanced shortcuts not only reduce the amount of code you have to write but also improve maintainability and readability. By embracing these modern features, you can write code that is both elegant and robust, saving you time and effort in the long run.

If you’ve ever wished you knew these tips sooner, now’s the time to put them into practice. Happy coding!

This is available on YouTube here.

Leave a Comment