Calling a C# constructor..

A

Alan Seunarayan

Hello all,
I need to know if I can call a C# constructor in the same way VB.NET and
JAVA can. For example:

class myClass {
public myClass() {
Console.WriteLine("Hello from constructor 1");
}

public myClass(string name) {
Console.WriteLine("{0} says \"Hello from constructor 2\"", name);
myClass(); //want to call the 1st constructor!!
}
}

many thanks and Happy New Year (in advance)

Alan Seunarayan
 
A

Alan Seunarayan

oh well, I think I have sorted it!
class myClass {
public myClass() {
Console.WriteLine("Hello from constructor 1");
}

public myClass(string name) :this() { //<---------fixed?
Console.WriteLine("{0} says \"Hello from constructor 2\"", name);
// myClass(); //want to call the 1st constructor!!
}
}

but if anyone knows better then please tell me.

thanks again
 
A

Alan Seunarayan

that idea sort of came to me just after posting, but there are always more
than one way to "skin a cat" and I just wanted to see if there was also
another way.

thank though

Alan
 
J

Jon Skeet [C# MVP]

Alan Seunarayan said:
that idea sort of came to me just after posting, but there are always more
than one way to "skin a cat" and I just wanted to see if there was also
another way.

Nope, that's it. Note that your first example wouldn't have worked in
Java either though, as (just like in C#) the other constructor (or the
base class's constructor) must be the first thing called.

See http://www.pobox.com/~skeet/csharp/constructors.html for more
information.
 

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