Share via


Compiler Error CS0445

Cannot modify the result of an unboxing conversion

The result of an unboxing conversion is a temporary variable. The compiler prevents you from modifying such variables because any modification would go away when the temporary variable goes away. To fix this, use a new value-type variable to store the intermediate expression, and assign the value to the new variable.

The following code generates CS0455:

namespace ConsoleApplication1
{
    // CS0445.CS
    class UnboxingTest
    {
        public static void Main()
        {
            Point p;
            p.x = 1;
            p.y = 5;
            object obj = p;

            // Generates CS0445:
            ((Point)obj).x = 2;

            // Use the following lines instead.
            //Point p2;
            //p2 = (Point)obj;
            //p2.x = 2;
            //obj = p2;
            // Verify the change.
            //Console.WriteLine(((Point)obj).x);
        }
    }

    public struct Point
    {
        public int x;
        public int y;
    }
}

Change History

Date

History

Reason

March 2009

Clarified the example.

Customer feedback.

September 2008

Added new example and explanation.

Customer feedback.