jnovacho
jnovacho

Reputation: 2903

Constructor chaining

I have following code:

    public MapReader(string fName) {
        FileName = fName;
    }

    public MapReader(){
        Console.WriteLine("Input valid file name:");
        string name = Console.ReadLine();
        this(name);
    }

Apparently this is Java approach, which is not working in C#. Is there any option which doesn't need added method for initialization?

Upvotes: 0

Views: 173

Answers (6)

Patrik Hägne
Patrik Hägne

Reputation: 17171

I don't quite like the approach of having a side effecting constructor like that, you could simulate the same thing like this:

public class MapReader
{
    private string fileName;

    private MapReader(Func<string> fileName)
    {
        this.fileName = fileName();
    }

    public MapReader(string fileName) : this(() => fileName)
    {
    }

    public MapReader() : this(() => 
        {
            Console.WriteLine("Input valid file name:");
            return Console.ReadLine();
        })
    {
    }
}

Upvotes: 0

Tadeusz
Tadeusz

Reputation: 6903

You can to do so:

public MapReader(string fName) {
   if (fName == null)
   {
     Console.WriteLine("Input valid file name:");
     fName = Console.ReadLine();
    }
    FileName = fName;
}

public MapReader() : this (null) {}

Upvotes: 0

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239794

Although I agree with others that having a dependency on the Console is probably not best for this class, this would work:

class MapReader
{
    public string FileName { get; private set; }
    public MapReader(string fName)
    {
        FileName = fName;
    }

    public MapReader() : this(ObtainNameFromConsole())
    {

    }

    private static string ObtainNameFromConsole()
    {
        Console.WriteLine("Input valid file name:");
        return Console.ReadLine();
    }
}

Upvotes: 2

asawyer
asawyer

Reputation: 17808

Maybe something like this?

public MapReader(string fName)
{
    FileName = fName;
}

public static MapReader FromConsole()
{
    Console.WriteLine("Input valid file name:");
    string name = Console.ReadLine();
    return new MapReader(name);
}

Upvotes: 0

Marco
Marco

Reputation: 57593

In C# you couldn' use that approach.
Try this:

private void setParam(string name) {
    FileName = name;
}

public MapReader(string fName) {
    setParam(fName);
}

public MapReader() {
    Console.WriteLine("Input valid file name:");
    string name = Console.ReadLine();
    setParam(name);
}

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 191037

You can't do this in C#. You will have to set the property in the other constructor.

Ideally, you should separate out the dependency on the console.

Upvotes: 3

Related Questions