6

I have 2 constructors, accepting different types of arguments:

public someClass(String s) {

    // the string is parsed to an int array.
    int[] array = doSomething(s);

    this(array);
}

public someClass(int[] array) {
    doSomethingElse(array);
}

However on the first constructor I get "Method name is expected". Is there a way to have a constructor call another after performing other actions, or is it simply a limitation of C#?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
fedetibaldo
  • 162
  • 2
  • 14
  • 1
    Both constructors belongs to same `class`, how it makes difference doing same thing in other constructor? (Just curious) – Hari Prasad Apr 06 '16 at 09:20

3 Answers3

14

As long as doSomething is static.

class someClass
{
    public someClass(String s)
        : this(doSomething(s))
    { }

    public someClass(int[] array)
    {
        doSomethingElse(array);
    }

    static int[] doSomething(string s)
    {
        //do something
    }
}
fedetibaldo
  • 162
  • 2
  • 14
Cheng Chen
  • 42,509
  • 16
  • 113
  • 174
3

You can't do that. But you could write

public SomeClass(string s) : this(doSomething(s)){}

which is perfectly fine, so long as int[] doSomething(string) is static.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

according to Call one constructor from another

public class SomeClass
{
    public SomeClass(string s) : this(dosomething(s))
    {

    }

    public SomeClass(int[] something)
    {
    }


    private static int[] dosomething(string)
    {
        return new int[] { };
    }
}

i would use a static method to achieve what you want

Community
  • 1
  • 1
Markus
  • 195
  • 1
  • 11