C # - Constructors and Inheritance

I have two classes declared as follows:

class Object1
{
    protected ulong guid;
    protected uint type;

    public Object1(ulong Guid, uint Type)
    {
        this.guid = Guid;
        this.type = Type
    }
    // other details omitted
}

class Object2 : Object1
{
    // details omitted
}

In the client code, I want to instantiate each object as follows:

Object1 MyObject1 = new Object1(123456789, 555);
Object2 MyObject2 = new Object2(987654321, 111);

How can I force Object2 to use the constructor of Object1? Thankyou.

+3
source share
3 answers
class Object2 : Object1
{
   Object2(ulong l, uint i ) : base (l, i)
   {
   }
}
+9
source

You must provide a constructor with the same signature for Object2, and then call the constructor of the base class:

class Object2 : Object1
{
    public Object2(ulong Guid, uint Type) : base(Guid, Type) {}
}
+1
source

Give Object2 such a constructor: -

public Object2(ulong Guid, uint Type): base(Guid, Type)
+1
source

Source: https://habr.com/ru/post/1702297/


All Articles