Alternatives to typedef or subclassing string in c#

c#, syntax, typedef

Solution

I've created a NuGet package called LikeType that provides `typedef`-like behavior in C# classes.

This is how you would use it:

class CustomerId : LikeType<string>
{
    public CustomerId(string id) : base(id) { }
}

Here is how the type will behave:

void ShowTypeBehavior()
{
    var customerId = new CustomerId("cust-001"); // create instance with given backing value
    string custIdValue = customerId; // implicit cast from class to backing type, sets 'custIdValue' to "cust-001"

    var otherCustomerId = new CustomerId("cust-002");
    var areEqual = customerId == otherCustomerId; // false
    var areNotEqual = customerId != otherCustomerId; // true
    var areEqualUsingMethod = customerId.Equals(otherCustomerId); // false

    var customerIdCopy = new CustomerId("cust-001"); // create separate instance with same backing value
    var isCopyEqual = customerId == customerIdCopy; // true. Instances are considered equal if their backing values are equal.
}

Problem

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.

Original source