I will take the opposite approach and say that do not do this. The best solutions published so far (use an alternative type, such as FileInfo or Uri for one of the overloads) seem a little hacky to me - they run counter to the principle of least surprise.
If you can use content only without a file name, this means that the file name is not significant. And similarly, if you can only build with a file name, then this is not necessary. Presumably, you can subsequently set the missing file name / content later, for example. setting the property:
MyObject myObject = new MyObject(fileName); myObject.Content = ... MyObject myObject = new MyObject(content); myObject.FileName = ...
Instead of trying to deal with it, select one of your options as the most important (file_name in the following example) and create two constructors as follows:
public MyObject(string fileName) : this(fileName, null) { } public MyObject(string fileName, string content) { ... implementation }
You can enable null for either or both parameters, if that makes sense. And you can insist that at least one of them is not null if necessary:
public MyObject(string fileName, string content) { if (fileName == null && content == null) throw new ArgumentException(...); ... }
In short, do not use hacks to circumvent restrictions like this.
Joe
source share