C # - call a constructor from another constructor after some calculations

I have 2 constructors taking 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 expected." Is there a way for the constructor to call another after performing other actions, or is it just a C # restriction?

+4
source share
3 answers

If doSomethingnot static.

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

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

    static int[] doSomething(string s)
    {
        //do something
    }
}
+7
source

You cannot do this. But you could write

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

which is great if int[] doSomething(string) static.

+2
source

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

    }

    public SomeClass(int[] something)
    {
    }


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

+2

All Articles