czubehead
czubehead

Reputation: 552

Empty constructor in inheriting class C#

I have written a simple generic 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 whether I can avoid writing that constructor in Bar class, because it does nothing special at all. PS: the parameter in constructor is necessary.

Upvotes: 9

Views: 3513

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500185

No, you can't. There's no inheritance of constructors. The constructor in Bar does do something: it provides an argument to the base constructor, using its own parameter for that argument. There's no way of doing that automatically.

The only constructor the compiler will supply for you automatically is one of equivalent to:

public Bar() : base()
{
}

for a concrete class, or for an abstract class:

protected Bar() : base()
{
}

... and that's only provided if you don't supply any other constructors explicitly.

Upvotes: 16

Related Questions