Use Flags feature in C# enumeration

Use Flags feature in C# enumeration

This is very useful, such as permissions, execution status, etc., can be saved in the database with an int type, and use enumeration in C# to deal with this problem.

    [Flags]
    public enum Permission
    {
        create = 1,
        read = 2,
        update = 4,
        delete = 8,        
    }

C#'s operations on this type are as follows:

            Permission permission = Permission.create | Permission.read | Permission.update | Permission.delete;
            Console.WriteLine("1, enumeration creation, and assignment...");
            Console.WriteLine(permission.ToString());
            Console.WriteLine((int)permission);

            permission = (Permission)Enum.Parse(typeof(Permission), "5");
            Console.WriteLine("2, convert by digital string......");
            Console.WriteLine(permission.ToString());
            Console.WriteLine((int)permission);

            permission = (Permission)Enum.Parse(typeof(Permission), "update, delete, read", true);
            Console.WriteLine("3. Convert through enumerated name string...");
            Console.WriteLine(permission.ToString());
            Console.WriteLine((int)permission);

            permission = (Permission)7;
            Console.WriteLine("4. Use digital force conversion directly...");
            Console.WriteLine(permission.ToString());
            Console.WriteLine((int)permission);

            permission = permission & ~Permission.read;
            Console.WriteLine("5. Remove an enumeration item...");
            Console.WriteLine(permission.ToString());
            Console.WriteLine((int)permission);

            permission = permission|Permission.delete;
            Console.WriteLine("6, add an enumeration item...");
            Console.WriteLine(permission.ToString());
            Console.WriteLine((int)permission);

Judging in the database:

AND (@permission IS NULL OR @permission=0 OR permission &@permission =@permission)

The above sql statement can also determine multiple permissions

Reference: https://cloud.tencent.com/developer/article/1513825 Use Flags feature in C# enumeration-Cloud + Community-Tencent Cloud