Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base Classes constructor being hit without calling it?

Tags:

c#

oop

Given the code:

public class A
{
    public A()
    {
        throw new Exception();
    }
}

public class B : A
{
    public B(int i)
    {

    }
}

Then running the line:

  var x = new B(2);

I would never expect A's constructor to get hit (unless I added base()) to the end of B's constructor declaration.

Oddly it seems to be getting hit (and throwing the exception). Is this default behavior? This has caught me out as I fully never expected A's constructor to be hit

like image 315
maxp Avatar asked Jul 04 '26 22:07

maxp


1 Answers

If you don't include any base(..) or this(..), it does the same thing as if you had base(). From the C# spec:


If an instance constructor has no constructor initializer, a constructor initializer of the form base() is implicitly provided. Thus, an instance constructor declaration of the form

C(...) {...}

is exactly equivalent to

C(...): base() {...}

You might've been looking to make A an abstract class, so that you cannot directly create an instance of A.

public abstract class A
{
}

public class B : A
{
    public B(int i)
    {

    }
}

public static void Main()
{
    // A a = new A(); // doesn't compile
    A a = new B(2); // valid
}
like image 187
Tim S. Avatar answered Jul 07 '26 12:07

Tim S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!