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?
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 means converting a value type to object. You are converting a reference type to another reference type, so this is not a boxing conversion.
No, boxing occurs when you convert a value type to an object.
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.
No.
Because emp1 is a reference type.
Boxing occurs when a value type is converted to an object, or an interface type.
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.