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.
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.
See more on this question at Stackoverflow