Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The as operator on structures?

Tags:

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?

like image 632
Royi Namir Avatar asked Nov 01 '12 11:11

Royi Namir


People also ask

What are structure operators?

Structure and Union MembersA structure is a user-defined data type which is a collection of an ordered group of data objects. Unlike the elements of an array, the data objects within a structure are of different data types. Each data object in a structure/union is called a member of the structure/union.

What is the -> operator in C++?

The -> is called the arrow operator. It is formed by using the minus sign followed by a greater than sign. Simply saying: To access members of a structure, use the dot operator. To access members of a structure through a pointer, use the arrow operator.

What does the -> mean in C?

The Arrow(->) operator exists to access the members of the structure or the unions using pointers.

What are the two access operators in structure in C?

Remarks. The member access operators . and -> are used to refer to members of struct , union , and class types. Member access expressions have the value and type of the selected member.


1 Answers

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.

like image 168
Marc Gravell Avatar answered Sep 22 '22 17:09

Marc Gravell