Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is interface inheritance allowed on a struct and why can a class not be inherited [closed]

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
{

}
like image 849
A.T. Avatar asked Nov 01 '25 05:11

A.T.


1 Answers

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

like image 62
Tigran Avatar answered Nov 03 '25 20:11

Tigran



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!