The situation
I have class that deals internally with many different types of file paths: some local, some remote; some relative, some absolute.
It used to be the case that many of its methods pass them around to each other as string
s, but it got very difficult to keep track of exactly what type of path each method was expecting.
The desired fix
So we essentially wanted to typedef
four different types to string
: RemoteRelative
, LocalRelative
, RemoteAbsolute
, and LocalAbsolute
. This way the static type checker could help developers make sure that they're providing and expecting string
s with the correct semantics.
Unfortunately, string
is sealed
in the BCL, so we couldn't do this with simple inheritance. And there's no simple typedef
, so we couldn't do it that way, either.
The actual fix
I ended up creating four different simple classes that each contain a readonly string
.
public struct LocalAbsolutePath {
public readonly string path;
public LocalAbsolutePath(string path) {
this.path = path;
}
}
That mostly works, but it ends up adding a little bit of undesired verbosity.
The question: Am I overlooking any alternatives that fit naturally into simple C# syntax?
Like I mentioned above, a C-style typedef string LocalAbsolutePath;
or even an F#-style type LocalAbsolutePath = string
would be my dream here. But even something that's a step that direction from custom classes would be great.
Your solution is good. You can fight the additional verbosity by adding a type conversion to string
, letting you use LocalAbsolutePath
wherever a string
could go.
public struct LocalAbsolutePath { // Making it a class would be OK too
private readonly string path; // <<=== It is now private
public LocalAbsolutePath(string path) {
this.path = path;
}
public static implicit operator string(LocalAbsolutePath p) {
return p.path;
}
}
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