tags:

views:

97

answers:

6

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?

A: 

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.

Justin Niessner
A: 

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

Gary
A: 

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.

Femaref
+2  A: 

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.

Rob Levine
+1  A: 

No.

Because emp1 is a reference type.

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

Alan
+5  A: 

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.

Ahmad Mageed
Probably worth clarifying the fact that although it isn't in the actual example the OP shows, it *may be* in a different situation.
Rob Levine