Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to typedef or subclassing string in c#

Tags:

syntax

c#

typedef

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 strings, 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 strings 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.

like image 442
sblom Avatar asked Apr 27 '12 19:04

sblom


1 Answers

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;
    }
}
like image 196
Sergey Kalinichenko Avatar answered Oct 03 '22 06:10

Sergey Kalinichenko