Calling a constructor from another constructor

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

    Calling a constructor from another constructor

    I am writing a class with several constructors and don't want to
    repeat the code. How can I call a constructor from another
    constructor?
    Example:
    class Foo
    {
    public Foo(string FName, string LName)
    {
    ...some code ...
    }

    public Foo(string FName)
    {
    Foo(FName, String.Empty);
    }

    }

    I keep getting "Foo is a type but is used like a variable" errors.

    How do I implement this?

    Tom P.
  • Peter Duniho

    #2
    Re: Calling a constructor from another constructor

    On Fri, 25 Jul 2008 13:29:00 -0700, Tom P. <padilla.henry@ gmail.comwrote:
    [...]
    public Foo(string FName, string LName)
    {
    ...some code ...
    }
    >
    public Foo(string FName)
    {
    Foo(FName, String.Empty);
    }
    >
    }
    >
    I keep getting "Foo is a type but is used like a variable" errors.
    >
    How do I implement this?
    Use the "this" keyword to call the constructor. Note that you'll have to
    put the call as part of the method declaration, rather than inside the
    method itself.

    Pete

    Comment

    • Jon Skeet [C# MVP]

      #3
      Re: Calling a constructor from another constructor

      Tom P. <padilla.henry@ gmail.comwrote:
      I am writing a class with several constructors and don't want to
      repeat the code. How can I call a constructor from another
      constructor?
      Example:
      class Foo
      {
      public Foo(string FName, string LName)
      {
      ...some code ...
      }
      >
      public Foo(string FName)
      {
      Foo(FName, String.Empty);
      }
      >
      }
      >
      I keep getting "Foo is a type but is used like a variable" errors.
      >
      How do I implement this?
      public Foo (string FName) : this(FName, String.Empty)
      {
      }

      You can call a base type constructor with "base" instead of "this".

      You can only call one other constructor, you have to do it with the
      above syntax (before anything else is executed, apart from variable
      initializers), and you can't use "this" anywhere in the call, either
      implicitly or explicitly.

      --
      Jon Skeet - <skeet@pobox.co m>
      Web site: http://www.pobox.com/~skeet
      Blog: http://www.msmvps.com/jon.skeet
      C# in Depth: http://csharpindepth.com

      Comment

      Working...