-1

I was reading through this answer: https://stackoverflow.com/a/15209464/1073672 Here is the code, copied for completeness and slightly simplified.

using System;

namespace Test
{
    interface IFoo
    {
        int Foobar{get;set;}
    }
    struct Foo : IFoo 
    {
        public int Foobar{ get; set; }
    }

    class Bar
    {
        // These two lines. I can not understand how they will work.
        Foo tmp;
        public IFoo Biz{ get { return tmp; } set { tmp = (Foo) value; } }

        public Bar()
        {
            Biz = new Foo(){Foobar=0};
        }
    }


    class MainClass
    {
        // This is not really important.
        public static void Main (string[] args)
        {
            var mybar = new Bar();
        }
    }
}

How do construction of Bar and assignment to Biz work? My take:

  1. In Bar constructor create a struct of type Foo() and set its Foobar = 0;
  2. Cast to type of IFoo by using boxing (?) (since Biz has type IFoo)
  3. Unbox the reference type IFoo to value type struct (Foo) and assign to tmp.

So is this description correct? This is really un/boxing even if we don't make use of the object class?

Community
  • 1
  • 1
user10607
  • 3,011
  • 4
  • 24
  • 31

1 Answers1

1

Your description is correct. Casting a struct to an interface causes boxing.

An interesting side effect is that assigning to Bar.Biz.Foobar will not cause any changes:

var mybar = new Bar();
mybar.Biz.Foobar = 2;
int fooBar = mybar.Biz.Foobar; // still 0

Mutable structs are evil.

Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39