Is casting to an interface a boxing conversion?

2020-04-02 08:17发布

I have an interface IEntity

public interface IEntity{
    bool Validate();
}

And I have a class Employee which implements this interface

public class Employee : IEntity{
    public bool Validate(){ return true; }
}

Now if I have the following code

Employee emp1 = new Employee();
IEntity ent1 = (IEntity)emp1; // Is this a boxing conversion?

If it is not a boxing conversion then how does the cast work?

标签: c# oop boxing
7条回答
三岁会撩人
2楼-- · 2020-04-02 09:00

No, since Employee is a class, which is a reference type rather than a value type.

From MSDN:

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object.

The aforementioned MSDN link has further examples that should help clarify the topic.

查看更多
登录 后发表回答