Home >Backend Development >C++ >How to Perform Bitwise Operations on Flags Enums in C#?

How to Perform Bitwise Operations on Flags Enums in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-13 11:44:43890browse

How to Perform Bitwise Operations on Flags Enums in C#?

Bitwise operations of [Flags] enumeration in C#

When using flag enumerations, it is crucial to master bit operations to seamlessly manage and manipulate individual bits within the enumeration value. This cheat sheet is intended to provide a brief overview of common bit operations in C#.

Set specific bits

To set a specific bit in the [Flags] enumeration, use the bitwise OR operator (|). Consider the following example:

<code class="language-csharp">FlagsEnum flags = FlagsEnum.None;
flags |= FlagsEnum.Bit4; // 设置位 4</code>

Remove specific bits

To remove a specific bit, use the bitwise AND operator and the negation of the bit. Here is an example:

<code class="language-csharp">if ((flags & ~FlagsEnum.Bit4) == 0) {
    // 已移除位 4
}</code>

Toggle specific bits

To switch a specific bit to its opposite value, use the bitwise XOR operator (^).

<code class="language-csharp">flags ^= FlagsEnum.Bit4; // 切换位 4</code>

Check if a specific bit is set

To determine whether a specific bit is set, use the bitwise AND operator and then compare.

<code class="language-csharp">if ((flags & FlagsEnum.Bit4) == FlagsEnum.Bit4) {
    // 设置了位 4
}</code>

Additional extension methods

Extending the System.Enum class with custom methods can further simplify bit operations. Consider the following extension:

<code class="language-csharp">public static class EnumExtensions {

    public static bool Has<T>(this Enum type, T value) =>
        (((int)(object)type & (int)(object)value) == (int)(object)value);

    public static T Add<T>(this Enum type, T value) =>
        (T)(object)(((int)(object)type | (int)(object)value));

    public static T Remove<T>(this Enum type, T value) =>
        (T)(object)(((int)(object)type & ~(int)(object)value));
}</code>

These methods provide convenient shortcuts for bitwise operations:

<code class="language-csharp">SomeType value = SomeType.Grapes;
value.Has(SomeType.Grapes); // true
value = value.Add(SomeType.Oranges);
value.Has(SomeType.Oranges); // true
value = value.Remove(SomeType.Grapes);
value.Has(SomeType.Grapes); // false</code>

The above is the detailed content of How to Perform Bitwise Operations on Flags Enums in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn