C# constructors annoy me!

Question

Look at these two classes

public class Test

{

public readonly string Name;

public Test(string name)

{

this.Name = name;

}

}

public class Test2 : Test

{

}

What annoys me is that trying to execute the following code gives me an
error that Test2 doesn''t have a constructor that takes 1 argument.

new Test2("Hello");

It''s pretty obvious that I want to use the inherited constructor, so why
wont C# use it?

Solution
Because constructors aren''t inherited.

Peter Morris [Droopy eyes software] wrote:
Look at these two classes

public class Test

{

public readonly string Name;

public Test(string name)

{

this.Name = name;

}

}

public class Test2 : Test

{

}

What annoys me is that trying to execute the following code gives me an
error that Test2 doesn''t have a constructor that takes 1 argument.

new Test2("Hello");

It''s pretty obvious that I want to use the inherited constructor, so why
wont C# use it?


change class Test2 to

public class Test2 : Test
{
public Test2(stirng name)
{
base(name);
}
}


"Peter Morris [Droopy eyes software]" <pe**@droopyeyes.no.com.spam>
wrote:
It''s pretty obvious that I want to use the inherited constructor, so why
wont C# use it?


Constructors aren''t methods, so they don''t need to conform to the LSP:
Barbara Liskov''s Substitution Principle.

In Delphi, constructors are effectively methods of the metaclass, which
acts as a statically allocated factory object. It therefore makes sense
to inherit constructors, because they really are methods.

The Liskov Substitution Principle means that if you''ve got an instance
of a class C descended from a class B, you should be able to use an
instance of C wherever you use an instance of B. Since constructors
aren''t methods, they don''t need this substitutability support.

The fact that a descendant class can hide inherited constructors can
actually be seen as a feature. Subclasses are exactly that: subclasses,
more specific and less general than their base superclass. It stands to
reason that they may require more information to construct, and thus
require a constructor which takes more information.

If the constructors from the base class were inherited, then this would
break the descendant class''s assumptions.

Alternatively, you can look at how things version. If you''ve written a
subclass C descended from your favourite component author''s B class, you
may have requirements for your constructors that you''ve fulfilled by
overriding the base class''s constructors. What if, in the next version,
B adds more constructors? It could break the assumptions of your class
C, because there would be a new way to construct it - that you didn''t
have the chance to validate yourself.

-- Barry