October 7, 2008

Boxing and Interfaces

public static void TestBoxing()
{
    // Create value
    SomeValueType myval = new SomeValueType();
    myval.X = 123;
    Debug.WriteLine("1. myval: " + myval.ToString());

    // box it
    object obj = myval;
    Debug.WriteLine("2. boxed: " + obj.ToString());

    // modify the contents in the box.
    ISomeValue iface = (ISomeValue)obj;
    iface.X = 456;
    Debug.WriteLine("3. After interface call: " + obj.ToString());

    // unbox it and see what it is.
    SomeValueType newval = (SomeValueType)obj;
    Debug.WriteLine("4. unboxed: " + newval.ToString());
    Debug.WriteLine("5. myval: " + myval.ToString());
    ((ISomeValue)myval).X = 789;
    Debug.WriteLine("6. myval: " + myval.ToString() + " obj: " + obj.ToString());
    ((ISomeValue)obj).X = 789;
    Debug.WriteLine("7. obj: " + obj.ToString());
    myval = (SomeValueType)obj;
    Debug.WriteLine("8. myval: " + myval.ToString());
}
Output:
1. myval: X=123
2. boxed: X=123
3. After interface call: X=456
4. unboxed: X=456
5. myval: X=123
6. myval: X=123 obj: X=456
7. obj: X=789
8. myval: X=789
Conclusion: To use an interface to modify a value type you must explicitly box and unbox it.

No comments: