Reputation: 4133
Cast a class to an interface is the same as convert a Class to another Class in C#?Does box or unboxing occurs in this process?
interface Area
{
string TxtArea
{
get;
set;
}
}
Convert to it interface:
public void Test()
{
ExternArea extArea = new ExternArea();
if(extArea is Area)
{
((Area)extArea).TxtArea = "voila";
}
}
Upvotes: 2
Views: 445
Reputation: 3002
As long as the ExternArea
object in your code sample is a reference type, then - no - no boxing operations will be performed. Boxing and unboxing refers to operations undertaken when value types are converted into objects.
For more information, please see Boxing and Unboxing (C# Programming Guide).
Upvotes: 0
Reputation: 9653
Boxing and unboxing have to do with packaging a value type inside an object, so it can be used as a reference type (allocated on the heap). When you're unboxing, you're getting such a value back from the "box". So no, this would not occur in this example.
Upvotes: 0
Reputation: 1500545
Assuming ExternArea
is a class rather than a value type (struct or enum), there's no boxing involved. Boxing only ever converts a value type to a reference type instance.
Note that using as
is generally preferred though:
Area area = extArea as Area;
if (area != null)
{
area.TxtArea = "voila";
}
Upvotes: 10
Reputation: 887453
Boxing only occurs if you convert a value type (a struct or a number) to a reference type (object
or an interface implemented by the struct
)
Casting a reference type (an instance of a class) to a different reference type (a base class or an interface implemented by the class) does not involve boxing.
Even so, you should not cast unnecessarily; instead, use the as
keyword, like this:
Area area = extArea as Area;
if (area != null)
{
area.TxtArea = "voila";
}
Upvotes: 2