Search code examples
azureazure-resource-managerpulumi

How to parse stack configuration string to EnumType struct in C# Pulumi Azure Native


Trying to get resource arguments from stack settings file (Pulumi.dev.yaml) and use configuration values to create resource, for example StorageAccount. For SkuName & Kind, readonly struct is being used (why not enum???) and if those were enum type, I could easily parse from string (stack configuration string value) to enum using Enum.Parse(EnumType, "stringValue").

How to parse stack configuration string value to (EnumType) struct?. Am I missing something? is there any better way to achieve that?

(.Net SDK uses ExpandableStringEnum: ExpandableStringEnum<SkuName>SkuName)


Solution

  • There's no direct way to do this, at the moment. You'll have to fall back to reflection to make this work:

    public static T ParseEnum<T>(string value)
    {
        return (T)typeof(T).GetProperty(value)?.GetValue(null);
    }
    
    // Usage example
    var sku = ParseEnum<SkuName>("Standard_LRS");
    

    An improvement is tracked in this issue, please upvote it.