AndreasW wrote:
Hi,
internal static class Program
{
public class foo
{
private int _id;
public foo()
{
}
public foo(int _id)
{
this._id = _id;
}
}
public class bar : foo
{
}
[STAThread]
private static void Main()
{
bar b = new bar(3); // constructor canot be found
}
}
why is this code not allowed ?
.... because in C# constructors are not inherited. If you want a
constructor for bar that takes an int, you have to say this:
public bar(int id) : base(id) { }
* I should add a note about "constructors are not inherited": if you do
not specify any constructor at all for a class, the compiler infers the
following:
public bar() : base() { }
If you then insert the int constructor, as above, you'll lose this
default constructor unless you explicitly write it. So, at the end of
it all, of you want bar to have constructors as foo, you need to say:
public bar() : base() { }
public bar(int id) : base(id) { }
By the way, one typically does not use the _ prefix for method
parameter names, just for private field names, so your foo constructor
would be better written as:
public foo(int id)
{
this._id = id;
}