tags:

views:

34

answers:

3

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?

+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
Think you want to add {} to the second example.
Dykam
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
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