Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Convert interfaces

Tags:

c#

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";
       }
    }
like image 247
ozsenegal Avatar asked Sep 05 '26 05:09

ozsenegal


1 Answers

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";
}
like image 163
Jon Skeet Avatar answered Sep 06 '26 19:09

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!