Forgot Syntax: calling a parameterized constructor of the same class from a non-parameterized one

S

Sathyaish

/* I am writing this C# program because I forgot the syntax for
calling a parameterized constructor from a non-parameterized one
within the same class.

I was coding in Java and just typed it like this:

public MyClass(String someParam)
{
}

public MyClass()
{
this.MyClass("Someparam");
}

The compiler complained and I remembered it was like this in Java:

public MyClass()
{
this("Someparam");
}

This led me to think that I am forgetting the way it is done in C#
and that my mistake was influenced by the way it is done in C#. Just
so that I do not forget how to do it in C#, I am writing this small
spike solution as a reminder.

I have now tried

this.MyClass("SomeParam");
MyClass("SomeParam"); and
this("SomeParam");

None of them seem to work. What's the correct way. I realize I have
forgotten the correct way.

*/
 
T

Tom Porterfield

Sathyaish said:
OK. RESOLVED.

It is

new SomeClass("SomeParam");

Got it.

Test that and you'll see it isn't doing what you want. See my reply to your
original.
 
T

Tom Porterfield

Sathyaish said:
/* I am writing this C# program because I forgot the syntax for
calling a parameterized constructor from a non-parameterized one
within the same class.

I was coding in Java and just typed it like this:

public MyClass(String someParam)
{
}

public MyClass()
{
this.MyClass("Someparam");
}

The compiler complained and I remembered it was like this in Java:

public MyClass()
{
this("Someparam");
}

What you want is:

public MyClass() : this ("Someparam")
{
}
 
S

Sathyaish

Thanks, Tom and Jon.

Ah! That was it. Thank you for the reminder, Tom. What I did earlier
was create a new object of the same class from an object of itself.
 

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