Calling a constructor from another

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Sathyaish

    Calling a constructor from another

    How does a constructor of one class call another of the same class?
    When would this mechanism make sense or be required?


    PS: Two instances I saw are:

    (a) While using the Singleton pattern
    (b) While using the Factory pattern

  • Daniel O'Connell [C# MVP]

    #2
    Re: Calling a constructor from another


    "Sathyaish" <Sathyaish@Yaho o.com> wrote in message
    news:1116814208 .670220.215150@ z14g2000cwz.goo glegroups.com.. .[color=blue]
    > How does a constructor of one class call another of the same class?[/color]

    public MyClass() : this(<arguments >)
    {
    ....
    }

    basically. You can also use base() to call a constructor on a base class[color=blue]
    > When would this mechanism make sense or be required?[/color]

    Generally, this allows you to specialize your constructors without redoing
    code. Imagine you have a parameterless constructor that sets a few
    properties to default values and one with a parameter that only sets one
    property. By calling the parameterless constructor from your single
    parameter one you bypass needing to re-write the code to set those
    properties.


    Comment

    • Jon Skeet [C# MVP]

      #3
      Re: Calling a constructor from another

      Sathyaish <Sathyaish@Yaho o.com> wrote:[color=blue]
      > How does a constructor of one class call another of the same class?[/color]

      See http://www.pobox.com/~skeet/csharp/constructors.html
      [color=blue]
      > When would this mechanism make sense or be required?
      >
      > PS: Two instances I saw are:
      >
      > (a) While using the Singleton pattern
      > (b) While using the Factory pattern[/color]

      I wouldn't expect either of these to use this pattern. I'd expect both
      of them to have static methods/properties/initialisers which called the
      constructor, but there's no need to have two constructors there.

      It makes sense to have multiple constructors when there are several
      parameters, some of which can take defaults. For instance:

      public Foo() : this (0, 0)
      {
      }

      public Foo (int x, int y)
      {
      this.x = x;
      this.y = y;
      }

      allows defaulting of x and y to 0 by overloading. Usually in this kind
      of situation all constructors end up calling the most specific one,
      passing in default values.

      --
      Jon Skeet - <skeet@pobox.co m>
      Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

      If replying to the group, please do not mail me too

      Comment

      Working...