Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Call a constructor from another constructor after some calculations [duplicate]

Tags:

c#

constructor

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

like image 699
fedetibaldo Avatar asked Apr 06 '16 09:04

fedetibaldo


2 Answers

Unless 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
    }
}
like image 177
Cheng Chen Avatar answered Nov 15 '22 05:11

Cheng Chen


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.

like image 30
Bathsheba Avatar answered Nov 15 '22 05:11

Bathsheba