0

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#?

Art Tema9
  • 11
  • 1
  • 1
  • In C++ structs and classes are the same thing with very minor differences. That's not the case in C#. – n0rd Mar 07 '22 at 07:19
  • @n0rd Yes, struct and class in c++ are almost the same. Both struct and class objects are allocated in place (on stack when it is a local variable or a parameter). Bu my question is if class/struct in C++ is (almost) the same as struct in C#, why can't I inherit struct in C#? – Art Tema9 Mar 07 '22 at 09:24
  • Primary motivation for banning inheritance is because of struct slicing (if you copy the struct as a base type you only get half an object) – Charlieface Mar 07 '22 at 11:36

0 Answers0