Calling a constructor from another constructor

T

Tom P.

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.
 
J

Jon Skeet [C# MVP]

Tom P. said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top