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 an Init-Only Setter Bypassed by Reflection

- 02.12.26 - ErcanOPAK

🔧 C#: Fix an Init-Only Setter Bypassed by Reflection

An init accessor is a compile-time construct — the C# compiler enforces that it can only be called from within an object initializer expression or a constructor, by emitting an IsExternalInit modifier the compiler itself checks for at the call site. That restriction exists nowhere in the actual IL method signature the runtime sees: an init-only property’s setter is just an ordinary set_PropertyName method with a modreq attached, and reflection APIs like PropertyInfo.SetValue don’t inspect or enforce modreqs at all, so any code calling through reflection can mutate a property the type’s own source code guarantees is only ever set once, completely silently, with no exception and no warning that the type’s intended immutability contract has just been violated.

🔎 The Problem

public class Order
{
    public int Id { get; init; }
    public decimal Total { get; init; }
}

var order = new Order { Id = 1, Total = 99.99m };

// Later, somewhere else in the codebase (a generic deserializer,
// a test helper, a mapping library using reflection under the hood):
typeof(Order)
    .GetProperty(nameof(Order.Total))!
    .SetValue(order, 0m);

Console.WriteLine(order.Total);
// 0 - the "immutable" record was mutated after construction with
// no compile error, no runtime exception, and no visible trace of it
// unless you already suspect reflection is involved somewhere

✅ Fix: Don’t Trust init Alone Where True Immutability Matters

  • Treat init as a compile-time authoring convenience, not a runtime guarantee — if a type’s immutability is load-bearing for correctness (a cache key, a value used in a hash set, anything shared across threads), back it with a readonly field set only in the constructor, which reflection genuinely cannot bypass the same way.
  • Audit any library or framework code in the project that uses reflection-based property setting (generic object mappers, certain serializers, test double/mocking frameworks) for whether it’s being pointed at init-only properties on types where that mutation would actually be a problem, since the capability existing in a dependency doesn’t mean it’s being exercised against your sensitive types specifically.
  • For types where this risk is realistic, add a unit test that explicitly attempts the reflection-based mutation and asserts it either throws or is caught by a code analyzer rule, turning an invisible footgun into a visible, intentional regression test instead of hoping nobody ever reaches for reflection near that type.

🚨 Why This Is Dangerous

  • A value object mutated after construction via reflection can silently invalidate any invariant the rest of the codebase assumes holds for that type — a hash code computed from a now-stale field, a cache keyed by a value that’s since changed underneath it — and because nothing throws, the resulting bug surfaces far away from the actual mutation, as a hard-to-explain data inconsistency rather than an obvious crash.

init-only properties are enforced by the compiler that writes your code, not by the runtime that executes it — and reflection talks to the runtime directly, which means it was never actually bound by that promise in the first place.

— C# Best Practice

Related posts:

C#: Use ObjectPool for Reusing Expensive Objects

C#: Use ObjectPool for Reusing Expensive Objects

C#: Use ArrayPool to Reduce GC Pressure

C#: Use ArrayPool to Reduce GC Pressure

C#: Use Pattern Matching with switch Expressions

C#: Use Pattern Matching with switch Expressions

Views: 0
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

The AI Prompt That Debugs IndexedDB Version Clashes
Photoshop: Fix Color Range Missing Skin Tones in Deep Shadow

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