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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With