rspec/rules/S3265/csharp/rule.adoc
2023-06-13 11:36:14 +02:00

61 lines
2.3 KiB
Plaintext

== Why is this an issue?
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum[Enumerations] are commonly used to identify distinct elements from a set of values.
However, they can also serve as https://en.wikipedia.org/wiki/Bit_field[bit flags], enabling bitwise operations to combine multiple elements within a single value.
[source,csharp]
----
// Saturday = 0b00100000, Sunday = 0b01000000, weekend = 0b01100000
var weekend = Days.Saturday | Days.Sunday; // Combining elements
----
When enumerations are used as bit flags, it is considered https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum#enumeration-types-as-bit-flags[good practice] to annotate the enum type with the https://learn.microsoft.com/en-us/dotnet/api/system.flagsattribute[FlagsAttribute]:
[source,csharp,diff-id=1,diff-type=noncompliant]
----
enum Permissions
{
None = 0,
Read = 1,
Write = 2,
Execute = 4
}
// ...
var x = Permissions.Read | Permissions.Write; // Noncompliant: enum is not annotated with [Flags]
----
The `FlagsAttribute` explicitly marks an enumeration as bit flags, making it clear that it uses bit fields and is intended to be used as flags.
[source,csharp,diff-id=1,diff-type=compliant]
----
[Flags]
enum Permissions
{
None = 0,
Read = 1,
Write = 2,
Execute = 4
}
// ...
var x = Permissions.Read | Permissions.Write; // Compliant: enum is annotated with [Flags]
----
Additionally, adding the `FlagsAttribute` to the enumeration enable a https://learn.microsoft.com/en-us/dotnet/api/system.flagsattribute#examples[better string representation] when using the https://learn.microsoft.com/en-us/dotnet/api/system.enum.tostring[Enum.ToString] method.
== Resources
=== Documentation
* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum[Enumeration in C#]
** https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum#enumeration-types-as-bit-flags[Enumeration types as bit flags]
* https://learn.microsoft.com/en-us/dotnet/api/system.flagsattribute[FlagsAttribute class]
* https://learn.microsoft.com/en-us/dotnet/api/system.enum.tostring[Enum.ToString method]
* https://en.wikipedia.org/wiki/Bit_field[Bit field - Wikipedia]
include::../rspecator.adoc[]