Skip to content

Add Enum.(Are)FlagsDefined #249

@Neme12

Description

@Neme12

Enum.IsDefined is great, but it's useless for Flags enums. I'd like a function that checks that in a certain value, all the flags it contains are defined in the enum, and it does not contain any undefined flags. I've wanted this ever since I discovered or used Enum.IsDefined - it seems like a missing feature, because IsDefined only works for non-flags enums. What about flags enums? The implementation would look like this, but using T of course instead of converting to ulong (this is my non-C# generated implementation):

extension(Enum)
{
    public static bool FlagsDefined<T>(T value)
        where T : struct, Enum
    {
        var flagsAttribute = typeof(T).GetCustomAttribute<FlagsAttribute>(); 
        if  (flagsAttribute is null)
            throw new InvalidOperationException("The enum type must be a [Flags] enum.");

        ulong allFlags = default;

        foreach (var flag in Enum.GetValues<T>())
            allFlags |= Convert.ToUInt64(flag);

        return (Convert.ToUInt64(value) | allFlags) == allFlags;
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions