Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
C#

C#: Fix a required Member the Compiler Enforces at Construction but a Reflection-Based Deserializer Silently Skips

- 04.10.26 - ErcanOPAK

🔧 The Required Property That Only the Compiler Was Actually Checking

Marking a property required makes the compiler refuse to build an instance through an object initializer unless every required property is set, which gives a strong, immediate guarantee at every call site in your own codebase that constructs the type directly. A library that builds the instance a different way entirely – creating it with no arguments and then setting properties one at a time through reflection, the way a generic mapper or an older serializer often does – never goes through the path the compiler actually checked, so it can hand back a half-populated object with no error, no warning, and no exception at all.

🔎 The Problem

public class Invoice
{
    public required string CustomerId { get; init; }
    public required decimal Total { get; init; }
}

// Your own code can never produce an incomplete Invoice this way -
// the line below simply does not compile:
// var bad = new Invoice { Total = 100 }; // error: required member
//                                        // 'CustomerId' must be set

// A generic reflection-based deserializer does not go through the
// initializer the compiler checked at all:
var invoice = (Invoice)Activator.CreateInstance(typeof(Invoice));
foreach (var prop in typeof(Invoice).GetProperties())
{
    if (document.TryGetValue(prop.Name, out var value))
        prop.SetValue(invoice, value);
}
// If the source document has no "Total" field, invoice.CustomerId can
// end up set while invoice.Total silently stays at zero - required
// was never actually enforced, because this path never touches the
// object initializer the compiler watches.

✅ Fix: Validate After Reflection-Based Construction, Don’t Trust required Alone

  • Do not trust required by itself to guard data coming from reflection-based deserialization – add an explicit validation step that runs after the object is populated and throws if a value that is required by design is still sitting at its type’s default.
  • For deserializers you control, prefer a constructor marked to set the required members and call it explicitly instead of a no-argument creation call followed by property-by-property reflection – that way the same guarantee protecting your own code also protects deserialized data.
  • Test every required property against each actual path that constructs the type, not only your own code – a mapper, a test-data builder, and a serializer are three separate entry points, and only one of them is ever checked by the compiler.

⚠️ Why This Is Easy to Miss

  • The compiler error for a missing required value is so immediate and strict in your own code that it quietly builds false confidence the type can never exist in an incomplete state anywhere in the whole application.
  • The gap only appears with one specific missing field in the input data combined with a reflection-based path, which is rare enough during normal development that it reliably passes testing and only surfaces against unexpected real-world data in production.

A required member is a promise the compiler enforces for the paths it can actually see – a reflection-based deserializer is not one of them, and it will hand you a broken promise without a word of complaint.

— C# Best Practice

Related posts:

C#: Use ArrayPool to Reduce GC Pressure

C#: Use ArrayPool to Reduce GC Pressure

Lightning-Fast Lookups in .NET Using MemoryCache

Lightning-Fast Lookups in .NET Using MemoryCache

C# Memory Management Deep Dive: GC, IDisposable, and Unmanaged Resources

C# Memory Management Deep Dive: GC, IDisposable, and Unmanaged Resources

Views: 10
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

The AI Prompt That Reviews a CI/CD Pipeline YAML File for Security and Secret-Exposure Risks Before You Merge It
Kubernetes: Fix a Job That Keeps Recreating Failed Pods Forever Because backoffLimit Was Never Set

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Most Read

  1. 01How to make theater mode the default for Youtube 1,080 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 997 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 996 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 873 views
  5. 05How to select distinct rows in a datatable in C# 869 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 672 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 631 views
  8. 08Average of all values in a column that are not zero in SQL 585 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 562 views
Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
Back to top
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com