C# Required Members — Complete Guide
In this tutorial, you'll learn about C# Required Members. We cover key concepts, practical examples, and best practices.
You create an object using an object initializer but forget to set a critical property. The code compiles and runs, but produces incorrect behavior because a mandatory field was left at its default. The required modifier (C# 11) forces callers to provide a value.
Wrong
public class UserConfig
{
public string ConnectionString { get; set; } // Forgot to set this
public int Timeout { get; set; } = 30;
}
var config = new UserConfig { Timeout = 60 };
// ConnectionString is null — will crash at runtime
Output: No compiler warning. Runtime NullReferenceException when ConnectionString is used.
Right
public class UserConfig
{
public required string ConnectionString { get; init; }
public int Timeout { get; set; } = 30;
}
var config = new UserConfig { Timeout = 60 };
// CS9035: Required member 'UserConfig.ConnectionString' must be set
Output: Compiler error CS9035. The caller must provide ConnectionString:
var config = new UserConfig { ConnectionString = "Server=...", Timeout = 60 };
// Compiles fine
The required modifier works with properties, fields, and init-only setters. It enforces that the member is initialized during construction or object initializer.
Prevention
- Use
requiredon properties that must be provided by the caller. - Use
requiredon init-only properties to enforce required initialization without a constructor parameter. - Use
requiredon record types to make positional parameters mandatory in object initializers. - Combine
requiredwithSetsRequiredMembersattribute on constructors for bypass scenarios. - Avoid
requiredon properties with sensible defaults. - Use
requiredin configuration objects and DTOs to catch missing values at compile time.
Common Mistakes with required member
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Required members enforce initialization contracts in DodaTech's configuration system. For more C# features, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro