Search code examples
c#.netcastingas-operator

The as operator on structures?


I don't get it. The As operator:

The as operator is used to perform certain types of conversions between compatible reference or nullable types.

Then why does the following work?

struct Baby : ILive
{
    public int Foo { get; set; }

    public int Ggg() 
    {
        return Foo;
    }
}

interface ILive
{
    int Ggg();
}

void Main()
{
    ILive i = new Baby(){Foo = 1} as ILive;    // ??????
    Console.Write(i.Ggg());                    // Output: 1
}
  • Baby is a struct, creating it will put value in stack. There is no reference involve here.

  • There are certainly no nullable types here.

Any explanation as to why I'm wrong?


Solution

  • Casting it as an interface will create a boxed copy on the managed heap , and return a reference to the boxed copy. The box implements the interface.