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 08:40

No, it's not.

Your instance of Employee is already a Reference Type. Reference Types are stored on the Heap so it doesn't need to be boxed/unboxed.

Boxing only occurs when you store a Value Type on the Heap or, in MSDN language, you could say:

Boxing is an implicit conversion of a Value Types (C# Reference) to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object.

查看更多
smile是对你的礼貌
3楼-- · 2020-04-02 08:40

Boxing means converting a value type to object. You are converting a reference type to another reference type, so this is not a boxing conversion.

查看更多
我只想做你的唯一
4楼-- · 2020-04-02 08:45

No, boxing occurs when you convert a value type to an object.

查看更多
该账号已被封号
5楼-- · 2020-04-02 08:50

In your example above, no but sometimes yes.

Boxing is the process of "boxing" a value type into a referenceable object; a reference type. In your example above, Employee is already a reference type, so it is not boxed when you cast it to IEntity.

However, had Employee been a value type, such as a struct (instead of a class), then yes.

查看更多
叼着烟拽天下
6楼-- · 2020-04-02 08:55

No.

Because emp1 is a reference type.

Boxing occurs when a value type is converted to an object, or an interface type.

查看更多
一纸荒年 Trace。
7楼-- · 2020-04-02 08:57

As others have said, casting a reference type to an interface is NOT an example of boxing, but casting a Value Type to an interface IS.

public interface IEntity {
    bool Validate();
}

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

public struct EmployeeStruct : IEntity {
    public bool Validate() { return true; }
}


//Boxing: A NEW reference is created on the heap to hold the struct's memory. 
//The struct's instance fields are copied into the heap.
IEntity emp2 = new EmployeeStruct(); //boxing

//Not considered boxing: EmployeeClass is already a reference type, and so is always created on the heap. 
//No additional memory copying occurs.
IEntity emp1 = new EmployeeClass(); //NOT boxing

//unboxing: Instance fields are copied from the heap into the struct. 
var empStruct = (EmployeeStruct)emp2;
//empStruct now contains a full shallow copy of the instance on the heap.


//no unboxing. Instance fields are NOT copied. 
var empClass = (EmployeeClass)emp2; //NOT unboxing.
//empClass now points to the instance on the heap.
查看更多
登录 后发表回答