How to call an overloaded class constructor

  • Thread starter Thread starter Chris Dunaway
  • Start date Start date
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
 
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.
 
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'.
 
...

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
 
Back
Top