Do I understand C# constructors?



  • In my library, I've set up the window classes to have two constructors. One takes parameters and the other reads parameters from a file based on the class name.

    public class ZWindow : Form
    {
      public ZWindow (ZStruct r)
      {
        this.TitleBar = r.TitleBar;
      }
      public ZWindow () : this(ZStruct.ReadCFG())
      {
      }
      public static ZWindow Shortcut () {return new ZWindow();}
    }
    public class ZWindow2 : ZWindow
    {
      public ZWindow2 (ZStruct r)
      {
        this.TitleBar = r.TitleBar;
      }
      public ZWindow2 () : this(ZStruct.ReadCFG())
      {
      }
      public static ZWindow2 Shortcut () {return new ZWindow2();}
    }
    

    How I thought constructors worked was like a function overload. Calling ZWindow() would pass through to ZWindow(ZStruct). I put a MessageBox.Show(CallerClassName); call in ReadCFG() to confirm some stuff.

    What I'm finding is, if I call the parameter constructor of ZWindow2, I get one alert box and, if I call the parameterless version, I get two. What's more, both alert boxes show "ZWindow2."

    I expected zero and one, respectively. But if the extra one is coming from the base class, why does it pop up the name of the derived class. What little detail did I miss here?



  • @Zenith you'll have call : base(zstruct) from zwindow2


  • 🚽 Regular

    @Zenith Are you sure you're not getting one of the alerts because of the instance being created in the static Shortcut method?

    Edit: never mind. Misread.



  • @Zecc Yes. What's weird is the alerts for both Window2.Shortcut() and new ZWindow2() are also out of order:

    ZStruct alert (ZWindow2)
    ZStruct alert (ZWindow2)
    ZWindow2 alert (ZWindow2(ZStruct))
    ZWindow2 alert (ZWindow2())

    I'd expect almost the reverse:

    ZWindow2 alert (ZWindow2())
    ZStruct alert (ZWindow2)
    ZWindow2 alert (ZWindow2(ZStruct))



  • @robo2 said in Do I understand C# constructors?:

    @Zenith you'll have call : base(zstruct) from zwindow2

    If I don't explicitly call a base constructor, shouldn't it be overridden by defining my own?


  • Discourse touched me in a no-no place

    @Zenith It must call some constructor of the base class. That is mandatory. If you don't say which and there is a no-arg version, that's what is called.



  • @dkf Please tell me the constructors are called in order from base to top.



  • @Zenith The base class is constructor is run right at the top of the subclass constructor. If your constructor is of the form:

    public ZWindow2() : base ("Hello")
    {
      // subclass constructor stuff
    }
    

    Then it will run the constructor of the base class that takes one string argument. If you don't have a ": base" at the end of your constructor signature, then it will run the no-arg constructor of the base class.


  • I survived the hour long Uno hand

    @Zenith

    .


Log in to reply