How to call an overloaded class constructor

C

Chris Dunaway

In VB.Net, you can call an overloaded class constructor from within an
overloaded constructor. How is this is achieved in C#?

Public Class A
Public Sub New()
MyClass.New(5) 'Call the overloaded constructor that takes
an int
End Sub

Public Sub New(i As Integer)
'Do something with I here
End Sub
End Class

How would you do this in C#? I tried this:

using System;
using System.Collections.Generic;
using System.Text;

namespace WindowsApplication1
{
class A
{
public A()
{
A(5);
}

public A(int i)
{
//do something with i here
}
}
}

and got this error:

'WindowsApplication1.A' is a 'type' but is used like a 'variable'

I also tried:

this.A(5);

and got this error:

'WindowsApplication1.A' does not contain a definition for 'A'


I found similar examples on MSDN but in VS2005, they had similar
errors.

Thanks
 
N

Nicholas Paldino [.NET/C# MVP]

Chris,

You need to declare your constructors like this:

using System;
using System.Collections.Generic;
using System.Text;

namespace WindowsApplication1
{
class A
{
// Use this to call an overloaded constructor.
// Use base to call a base constructor.
public A() : this(5)
{
}

public A(int i)
{
//do something with i here
}
}
}

Hope this helps.
 
M

Marcus Andrén

In VB.Net, you can call an overloaded class constructor from within an
overloaded constructor. How is this is achieved in C#?

using System;
using System.Collections.Generic;
using System.Text;

namespace WindowsApplication1
{
class A
{
public A() : this(5)
{
}

public A(int i)
{
//do something with i here
}
}
}

To call an overloaded constructor you use the the 'this' keyword
directly after the method header. The overloaded constructor will be
called before the original constructor is executed.

The same syntax is used when calling a specific constructor in the
base class, but using the 'base' keyword instead of 'this'.
 
B

Bjorn Abelli

...

How would you do this in C#? I tried this:


namespace WindowsApplication1
{
class A
{
public A() : this(5) // Note the initialization list
{
}

public A(int i)
{
//do something with i here
}
}
}

// Bjorn A
 

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