Home >Backend Development >C++ >Can Reflection Bypass Private Readonly Field Immutability in C#?

Can Reflection Bypass Private Readonly Field Immutability in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-17 18:04:14873browse

Can Reflection Bypass Private Readonly Field Immutability in C#?

Modifying Private Readonly Fields in C# Using Reflection

While private readonly fields in C# are designed to prevent modification after object initialization, reflection provides a mechanism to bypass this restriction. This means that, despite the readonly keyword, the values of these fields can be changed after the constructor completes.

Let's illustrate this with an example:

<code class="language-csharp">public class Foo
{
    private readonly int bar;

    public Foo(int num)
    {
        bar = num;
    }

    public int GetBar()
    {
        return bar;
    }
}</code>

Here, Foo contains a private readonly int bar. We can modify bar using reflection:

<code class="language-csharp">Foo foo = new Foo(123);
typeof(Foo).GetField("bar", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(foo, 567);</code>

This code snippet uses reflection to access the private bar field and sets its value to 567. This demonstrates that the readonly modifier, in conjunction with private access, doesn't guarantee absolute immutability when reflection is employed. It's crucial to understand this behavior to avoid unexpected issues and maintain code integrity.

The above is the detailed content of Can Reflection Bypass Private Readonly Field Immutability in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn