The as operator on structures?
-
25-07-2021 - |
Question
I don't get it. The As
operator:
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 instack
. There is no reference involve here.There are certainly no nullable types here.
Any explanation as to why I'm wrong?
La 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.
Autres conseils
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.
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.