Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty constructor in inheriting class C#

Tags:

c#

oop

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.

like image 767
czubehead Avatar asked Jun 22 '15 16:06

czubehead


People also ask

Do inherited classes inherit constructors?

In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class.

Can you have an empty constructor?

Empty Constructor in Java When creating a constructor, we must ensure that the constructor has the same name as the class and doesn't return any value; an empty constructor is a constructor that doesn't require any parameters, and a default constructor can also be the empty constructor.

Does an inherited class need a constructor?

This is all or nothing - you cannot inherit only some constructors, if you write this, you inherit all of them. To inherit only selected ones you need to write the individual constructors manually and call the base constructor as needed from them. Historically constructors could not be inherited in the C++03 standard.

Is an empty constructor necessary?

An empty constructor is needed to create a new instance via reflection by your persistence framework. If you don't provide any additional constructors with arguments for the class, you don't need to provide an empty constructor because you get one per default.


1 Answers

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.

like image 51
Jon Skeet Avatar answered Oct 08 '22 23:10

Jon Skeet