If you make an inherited class in C# (VS2005) do you need to explicitly call the constructor of the higher class, or will it be called automatically?
views:
34answers:
3
+3
A:
The default (parameterless) constructor will automatically be invoked if not supplied.
In other words, these are equivalent:
public Foo() : base() {}
and
public Foo() {}
assuming that Foo's base has a parameterless constructor.
On the other hand, if the base only has a constructor with parameters like this:
protected MyBase(IBar bar) {}
then
public Foo() {}
will not compile. In this case you must explicitly call the base with the appropriate parameter - e.g.
public Foo(IBar bar) : base(bar) {}
Mark Seemann
2010-06-29 07:54:38
Think you want to add {} to the second example.
Dykam
2010-06-29 07:57:09
A:
If the base class has a default constructor that will be invoked automatically. If there is no default constructor you must invoke one explicitly.
AbstractCode
2010-06-29 07:55:19
A:
The base class' default constructor will be automatically called if you do not specify one.
Example code:
public class ClassA
{
protected bool field = false;
public ClassA()
{
field = true;
}
}
public class ClassB : ClassA
{
public ClassB()
{
}
public override string ToString()
{
return "Field is " + field.ToString();
}
}
class Program
{
static void Main(string[] args)
{
ClassB target = new ClassB();
Console.WriteLine(target.ToString());
Console.ReadKey();
}
}
This will show that the 'field' value is set to true, even though the ClassA constructor was not explicitly called by ClassB.
Dr Herbie
2010-06-29 08:01:50