Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6365547
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T00:18:26+00:00 2026-05-25T00:18:26+00:00

I have a situation where I have a simple, immutable value type: public struct

  • 0

I have a situation where I have a simple, immutable value type:

public struct ImmutableStruct
{
    private readonly string _name;

    public ImmutableStruct( string name )
    {
        _name = name;
    }

    public string Name
    {
        get { return _name; }
    }
}

When I box an instance of this value type, I would normally expect that whatever it is that I boxed would come out the same when I do an unbox. To my big suprise this is not the case. Using Reflection someone may easily modify my box’s memory by reinitializing the data contained therein:

class Program
{
    static void Main( string[] args )
    {
        object a = new ImmutableStruct( Guid.NewGuid().ToString() );

        PrintBox( a );
        MutateTheBox( a );
        PrintBox( a );;
    }

    private static void PrintBox( object a )
    {
        Console.WriteLine( String.Format( "Whats in the box: {0} :: {1}", ((ImmutableStruct)a).Name, a.GetType() ) );
    }

    private static void MutateTheBox( object a )
    {
        var ctor = typeof( ImmutableStruct ).GetConstructors().Single();
        ctor.Invoke( a, new object[] { Guid.NewGuid().ToString() } );
    }
}

Sample output:

Whats in the box: 013b50a4-451e-4ae8-b0ba-73bdcb0dd612 ::
ConsoleApplication1.ImmutableStruct Whats in the box:
176380e4-d8d8-4b8e-a85e-c29d7f09acd0 ::
ConsoleApplication1.ImmutableStruct

(There’s actually a small hint in the MSDN that indicates this is the intended behavior)

Why does the CLR allow mutating boxed (immutable) value types in this subtle way? I know that readonly is no guarantee, and I know that using “traditional” reflection a value instance can be easily mutated. This behavior becomes an issue, when the reference to the box is copied around and mutations show up in unexpected places.

One thing I have though about is that this enables using Reflection on value types at all – since the System.Reflection API works with object only. But Reflection breaks apart when using Nullable<> value types (they get boxed to null if they do not have a Value). Whats the story here?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T00:18:27+00:00Added an answer on May 25, 2026 at 12:18 am

    Boxes aren’t immutable as far as the CLR is concerned. Indeed, in C++/CLI I believe there’s a way of mutating them directly.

    However, in C# the unboxing operation always takes a copy – it’s the C# language which prevents you from mutating the box, not the CLR. The IL unbox instruction merely provides a typed pointer into the box. From section 4.32 of partition III of ECMA-335 (the unbox instruction):

    The unbox instruction converts obj (of type O), the boxed representation of a value type, to valueTypePtr (a controlled-mutability managed pointer (§1.8.1.2.2), type &), its unboxed form. valuetype is a metadata token (a typeref, typedef or typespec). The type of valuetype contained within obj must be verifier-assignable-to valuetype.

    Unlike box, which is required to make a copy of a value type for use in the object, unbox is not required to copy the value type from the object. Typically it simply computes the address of the value type that is already present inside of the boxed object.

    The C# compiler always generates IL which results in unbox being followed by a copying operation, or unbox.any which is equivalent to unbox followed by ldobj. The generated IL isn’t part of the C# spec of course, but this is (section 4.3 of the C# 4 spec):

    An unboxing operation to a non-nullable-value-type consists of first checking that the object instance is a boxed value of the given non-nullable-value-type, and then copying the value out of the instance.

    Unboxing to a nullable-type produces the null value of the nullable-type if the source operand is null, or the wrapped result of unboxing the object instance to the underlying type of the nullable-type otherwise.

    In this case, you’re using reflection and therefore bypassing the protection offered by C#. (It’s a particularly odd use of reflection too, I must say… calling a constructor "on" a target instance is very strange – I don’t think I’ve ever seen that before.)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this simple situation: @Entity public class Customer{ @ManyToMany(fetch=FetchType.EAGER) @Cascade(CascadeType.SAVE_UPDATE) private List<Product> products=new
I have a situation in C# where I have a list of simple types.
Situation: I have a simple XML document that contains image information. I need to
The situation is very simple, I have two panel. In the event of OnMouseOver
I have a simple parent-child situation where the parent can have multiple children. The
All, my situation is that I have the basic route, plus some other simple
i have situation like this: class IData { virtual void get() = 0; virtual
I have a simple situation. A large organisation is using several different versions of
Simple situation. I have a list of lists, almost table like, and I am
The situation is simple. I have a datagrid that gets its data from a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.