I have the following class hierarchy.
public abstract class ResourceBase { }
public abstract class WebResourceBase : ResourceBase {
public ResourceBase LocalPath { get; set; }
public ResourceBase FtpPath { get; set; }
}
public class JavaScript : WebResourceBase { }
What I would like to do is have a declaration like so.
new JavaScript() {
LocalPath = "/path/goes/here/1.js",
FtpPath = "ftp://path/goes/here/1.js"
}
The obvious answer here would be to use implicit operators but the problem is that I want to assign a derived type to those properties which is the same as the declared type so LocalPath and FtpPath would be of type JavaScript.
I’d like my solution to be more flexible than what I have at the moment. This code just makes my skin crawl. Was hoping there was a way using reflection and I have tried looking for information using the StackTrace class but no luck. Any help would be appreciated. Thanks.
public abstract class ResourceBase {
public static implicit operator ResourceBase(string path) {
if (path.EndsWith(".js"))
return new JavaScript(path);
// etc...
}
}
This assumes that
WebResourceBaseis actually meant to inheritResourceBase.You won’t be able to make the implicit operator look much nicer, unfortunately – generics won’t work here.
Alternative: Generics to constrain ResourceBase
Now that I’ve re-read it and understand what you’re after, one option is to amend your classes to include a generic parameter referencing derived classes (sort of like a self-reference):
Then you will see that in
JavaScript, the propertiesLocalPathandFtpPathare now of typeJavaScriptalso.Now your assignment will only accept
JavaScripttypes:The benefit of this approach is it will constrain the base properties to be of the current type or more derived, not less derived.
Alternative: Explicit parsing instead of
implicitoperatorIf you need to leave the
LocalPathandFtpPathvariables asResourceBase, or otherwise cannot use generics here, your implicit operator will start to get confusing. Better to provide something explicit like a static method:Alternative: Class hierarchy parsing instead of
implicitoperatorBake the concept of consuming strings into the types via constructors and make the properties public read-only:
To be honest, most of this seems a little overkill just to get two properties set as a particular type from a string, you have loads of options – even the implicit operator will work.
Pick the one that is easiest to understand. Operator overloading tends to be somewhat hidden unless you go digging for it.