Skip to main content

Command Palette

Search for a command to run...

Required Parameters in C# 13: A Cleaner Way to Write Methods

Updated
2 min read
Required Parameters in C# 13: A Cleaner Way to Write Methods

C# 13, currently in preview with .NET 10, introduces a long-awaited feature: required method parameters. While the required keyword has been available for properties since C# 11. This new enhancement lets developers enforce method arguments more declaratively, improving readability and reducing boilerplate validation code.

In this post, we'll explain required parameters, how they differ from optional and nullable ones, and how to start using them immediately.


The Problem with Traditional Method Parameters

Traditionally, when a method expects non-null input, you’re forced to write boilerplate like this:

public void SendEmail(string? recipient)
{
    if (string.IsNullOrWhiteSpace(recipient))
        throw new ArgumentException("Recipient is required", nameof(recipient));

    // logic here
}

Even with nullable annotations, the compiler won't enforce non-null at compile time unless you're using nullable reference types strictly.


The New required Parameters

C# 13 now lets you mark parameters as required, just like you do with properties. The compiler ensures they’re supplied at the call site.

public void SendEmail(required string recipient)
{
    // No need for null checks unless you're doing deeper validation
    Console.WriteLine($"Sending to {recipient}");
}

If the caller omits the parameter or passes null, the compiler throws an error — before runtime.

Syntax

void MyMethod(required string name, int age)
  • Only applies to reference types (currently).

  • Cannot be combined with params or optional parameters.

  • Works well with overloading and pattern-matching.


Real-World Use Case

Suppose you're building an API layer:

public IActionResult RegisterUser(required string username, required string email)
{
    // No need to write null/empty validation unless you're doing regex/email format checks
    _logger.LogInformation($"User: {username}, Email: {email}");
    return Ok();
}

The controller is cleaner, and contract enforcement is built into the compiler.


Gotchas and Edge Cases

  • Required is not yet compatible with value types (though they must be passed anyway).

  • Default values are not allowed on required parameters.

  • Refactoring existing methods to include required might break existing call sites.

  • This is a preview feature, so you’ll need the latest .NET 10 SDK and enable preview features in your .csproj:

<LangVersion>preview</LangVersion>

Summary

Required parameters in C# 13 are a simple but powerful addition that promotes cleaner, more self-documenting code. By shifting enforcement to compile time, they reduce runtime bugs and eliminate redundant checks.

If you're already using required for object properties, this method-level enhancement will feel like a natural progression.


References