Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create two constructors that act differently but receive the same data type?

public class Parser
{
    Downloader download = new Downloader();
    HtmlDocument Page;

    public Parser(string MovieTitle)
    {
        Page = download.FindMovie(MovieTitle);
    }

    public Parser(string ActorName)
    {
        Page = download.FindActor(ActorName);
    }
}

I want to create a constructor that will allow other developers who use this library to easily create a Parser object with the relevant HtmlDocument already loaded as soon as it's done creating it.

The problem lies in that a constructor cannot exist twice with the same type of parameters. Sure I can tell the logical difference between the two parameters, but the computer can't.

How to handle this?

like image 433
Sergio Tapia Avatar asked Nov 29 '22 05:11

Sergio Tapia


1 Answers

Use a couple static methods instead:

public class Parser
{
    Downloader download = new Downloader();
    HtmlDocument Page;

    private Parser() { } // prevent instantiation from the outside

    public static Parser FromMovieTitle(string MovieTitle)
    {
        var newParser = new Parser();
        newParser.Page = newParser.download.FindMovie(MovieTitle);
        return newParser;
    }

    public static Parser FromActorName(string ActorName)
    {
        var newParser = new Parser();
        newParser.Page = newParser.download.FindActor(ActorName);
        return newParser;
    }
}
like image 124
mmx Avatar answered Dec 04 '22 13:12

mmx