In C#, structs are value types, both interface and class are reference type. Then, why can struct not inherit a class but it can instead inherit an interface?
class a { }
public struct MyStruct : a //This will not be allowed.
{
}
interface a { }
public struct MyStruct : a // and this will work
{
}
Interface is not a reference or value type by itself. Interface is a contract, which reference or value type subscribe to.
You probably refer to a fact that struct that inherits from interface is boxed.
Yes. This is because in C# struct members are defined like virtual members. And for
virtual members you need to maintain virtual table, so you need a reference type.
Let's do following to prove this:
public interface IStruct {
string Name {get;set;}
}
public struct Derived : IStruct {
public string Name {get;set;}
}
Now, let's call it in this way:
//somewhere in the code
public void ChangeName(IStruct structInterface) {
structInterface.Name = "John Doe";
}
//and we call this function as
IStruct inter = new Derived();
ChangeName(inter);
//HERE NAME IS CHANGED !!
//inter.Name == "John Doe";
This is not something we would expect from value type, but this is exactly as reference types work. So here what happens is that value typed instance of Derived is boxed to reference type constructed on top of IStruct.
There are performance implications and also misleading behavior, like in this case, of the value type that starts to behave like a reference type.
More on this subject can have a look on:
C#: Structs and Interface
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With