Empty constructor in C # class inheritance

I wrote a simple general class in C #.

class Foo<T>
{
   public object O{get;set;}
   public Foo(object o)
   {
      O=o;
   }
}

and another class inheriting from it

class Bar:Foo<object>
{
   public Foo(object o):base(o)
   { }
}

My question is, can I avoid writing this constructor in the class Bar, because it does nothing at all. PS: a parameter is needed in the constructor.

+4
source share
1 answer

No, you can’t. There is no inheritance of constructors. The constructor in Bardoes something: it provides an argument to the base constructor, using its own parameter for this argument. There is no way to do this automatically.

The only constructor that the compiler will automatically provide you with is equivalent:

public Bar() : base()
{
}

for a particular class or for an abstract class:

protected Bar() : base()
{
}

... and this is provided only if you do not provide any other constructors explicitly.

+11
source

All Articles