C#C
C#2y ago
orlac

Pattern matching `Type` in a way that can be assigned to a `const` variable... is it possible?

I'd like to come up with something where i can just have a lookup for a bunch of GUIDs that are assigned for each type. I write this, but it won't compile (I end up with error: CS8121 - but MS docs don't have any specifics about it for some reason). I had it implemented by taking in an object, which worked ok (it compiled at least), but I need to be able to do this lookup and assignment before any objects exist since it needs to be assigned to a const member variable. Any help/workarounds would be appreciated... it doesn't need to be structured exactly like this for the input or patterns in the switch, i'm just not too sure what other options I have when it comes to assigning the result to a const variable:
internal static class Constants {
    public static string GUID(Type type) {
        return type switch {
            TypeA   => "DEADBEEF-FEEE-FEEE-CDCD-000000000000",
            TypeB   => "DEADBEEF-FEEE-FEEE-CDCD-000000000001",
            TypeC   => "DEADBEEF-FEEE-FEEE-CDCD-000000000002",
            TypeEtc => "DEADBEEF-FEEE-FEEE-CDCD-000000000004",
    
            null => throw new ArgumentNullException(
                $"GUID lookup failed, {nameof(type)} is null"
            ),
            _ => throw new ArgumentException(
                $"GUID lookup failed, type {type.Name} missing from GUID map"
            ),
        };
    }
}

The assignment was planned to be something like this:
private const string GUID = Constants.GUID(TypeA);


It's probably also worth mentioning this is for a VS2022 extension just to keep all of the extension component GUIDs defined in one place, so if there are alternatives to doing something like this (like some Visual Studio specific resource/config specific utilities I haven't found yet or something like that) i'd be happy to hear any suggestions anyone might have for this type of thing.
Was this page helpful?