Home >Backend Development >C++ >Can Reflection Modify C#'s Private Readonly Fields?

Can Reflection Modify C#'s Private Readonly Fields?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-17 18:16:09681browse

Can Reflection Modify C#'s Private Readonly Fields?

Using Reflection to Modify Private Readonly Fields in C#

Reflection in C# offers powerful capabilities, including the ability to manipulate even private readonly fields. Let's examine whether we can alter a private readonly field after an object has been created.

Consider this example:

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

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

    public int GetBar()
    {
        return bar;
    }
}

Foo foo = new Foo(123);
Console.WriteLine(foo.GetBar()); // Outputs 123</code>

Modifying the Field with Reflection

Now, let's use reflection to change the bar field:

<code class="language-csharp">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.

The Result

After this reflection operation, the value of bar has indeed changed:

<code class="language-csharp">Console.WriteLine(foo.GetBar()); // Outputs 567</code>

This demonstrates that despite being declared private readonly, reflection allows modification of the field's value after object creation. While this is possible, it's generally considered bad practice and should be avoided unless absolutely necessary due to potential unforeseen consequences and maintainability issues.

The above is the detailed content of Can Reflection Modify C#'s Private Readonly Fields?. 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