7

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#?

1
  • 1
    Both constructors belongs to same class, how it makes difference doing same thing in other constructor? (Just curious) Commented Apr 6, 2016 at 9:20

3 Answers 3

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.