Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create two constructor overloads, both taking only one string parameter?

For example, you want an object to be possibly initialised in two ways, using a file path and using a string. Normally both constructors should take one string parameter, MyObject(string file) and MyObject(string content), but it is impossible to overload this way. What do you suggest?

Edit: In the first case, the file path is also needed, so please don't suggest a solution that reads the file content and just pass the content to the other constructor.

like image 772
Louis Rhys Avatar asked Feb 15 '11 05:02

Louis Rhys


1 Answers

I'm not a C# programmer but this looks like a job for the static factory method pattern:

class MyObject {
  public static MyObject FromContent(string content) {
    return new MyObject(content);
  }

  public static MyObject FromFile(string path) {
    return new MyObject(ReadContentFromFile(path));
  }
}

Then you can do

MyObject object = MyObject.FromFile("/some/path");

which is even more readable than using a regular constructor.

like image 110
sjr Avatar answered Oct 10 '22 21:10

sjr