I am wondering why is there no struct inheritance in C# similar to what we have in C++. All I want is to extend the base class with some members. I know it wouldn't make polymorphism possible, but extending a struct by inheriting it would save a lot of code
C++ example:
struct A
{
int x;
virtual void func()
{
cout << "Hi from A \n";
}
}
struct B : public A
{
int y;
void func() override
{
cout << "Hi from B \n";
}
}
int main()
{
B b;
A a;
// A = b You cannot do this, because B requires more memory (as it is an object not just a pointer)
// Thus no polymorphism is possible
a.func() // "Hi from A"
b.func() // "Hi from B"
// No problem accessing properties of parent
b.x = 1;
}
We can't assign object of derived class to an object of the base class or use polymorphism, but can we easily extend the base class with some members
C# example:
struct A
{
public int X;
public void Func()
{
Console.WriteLine("Hi");
}
}
struct B
{
// We must now write the same code again just to add a property as C# doesn't allow struct inheritance
public int X;
// All the code below is copied from A, which violates the DRY principle
public void Func()
{
Console.WriteLine("Hi");
}
public int Y;
}
So how do I extend a struct in C#?