The as operator on structures?

646 Views Asked by At

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?

3

There are 3 best solutions below

2
On BEST ANSWER

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.

0
On

You simply cast with reference type ILive nullable value, so no error is thrown. However if you try this commented code, you will get an error.

Baby b = new Baby ();
 object o = b;
//Baby bb = o as Baby ;

This is because you are trying to cast with as to value type and that can not be null.

2
On

It works because the right hand side is an interface. The condition is that the right hand side can accept null as value, i.e. it's a reference type or a nullable value type. Interfaces are a reference types. In this case the code will box the struct and then cast the boxed object to the interface.