Moberg
Moberg

Reputation: 793

Chained constructers in C# - using intermediate logic

From this thread : http://geekswithblogs.net/kaju/archive/2005/12/05/62266.aspx someone asked (in the comments) this question:

is there any way to do something like this:

public FooBar(string fooBar)
{
string[] s = fooBar.split(new char[] { ':' });
this(s[0], s[1]);
}

public Foo(string foo, string bar)
{
...
} 

Well, I've run into the a situation where I need the same thing. Is it somehow possible? Thanks in advance.

EDIT

I meant this

public Foo(string fooBar)
{
string[] s = fooBar.split(new char[] { ':' });
this(s[0], s[1]);
}

public Foo(string foo, string bar)
{
...
} 

Foo is a constructor.

My problem is that I have to do a lot of logic - including some IO stuff - before calling the other constructor.

Upvotes: 2

Views: 114

Answers (2)

McKay
McKay

Reputation: 12604

As you mention, you may need to do "some IO stuff - before calling the other constructor." Maybe you want a static creation method?

public static FooBar LoadFromFile(string fileName)
{
    var foo = "Default";
    var bar = "Other Default";
    // load from the file, do a bunch of logic, 

    return new FooBar(foo, bar);
}

Upvotes: 1

Tim Robinson
Tim Robinson

Reputation: 54724

Not directly, but:

public FooBar(string fooBar)
    : this(fooBar.Split(new char[] { ':' }))
{
}

private FooBar(string[] s)
    : this(s[0], s[1])
{
}

public FooBar(string foo, string bar)
{
...
}

Upvotes: 14

Related Questions