dotnet / dotnet/roslyn

Flag Enum Warning Enum.HasFlag(Enum) for Zero

Open
#83,779 1 comment 0 reactions 0 assignees View on GitHub
Area-IDE Feature Request
Dominant language
C#
Stars
20.7k
Forks
4.3k
PR merge metrics
PR metrics pending

Description

**Brief description:**

There are scenarios where it makes no sense to check Enum.HasFlag against zero, because it is always true.
Like here:

```csharp
[Flags]
public enum Permissions
{
None = 0,
Read = 1,
Write = 2,
Delete = 4
}
```

Permission is not None when the enum is higher than zero.
In this scenario, it is for zero only useful to check `== Permissions.None`

I would like to have an Attribute that throw an Compiler Warning when `.HasFlag(Permission.None)` or `.HasFlag(0)` is used.
If the value cannot be determined at compile time, it should be ignored. This Issue is for compile-time constants to improve code clarity.

My Idea is Like:
```csharp
[Flags]
public enum Permissions
{
[NotFlagable]
None = 0,
Read = 1,
Write = 2,
Delete = 4
}
```

Or an alternative:
```csharp
[Flags]
[ZeroIsNotFlagable]
public enum Permissions
{
None = 0,
Read = 1,
Write = 2,
Delete = 4
}
```

**Languages applicable:**

C# and VB

**Code example that the analyzer should report:**

```csharp
[Flags]
public enum Permissions
{
[NotFlagable]
None = 0,
Read = 1,
Write = 2,
Delete = 4
}

public class Example
{
public void Check(Permissions permission)
{
if (permission.HasFlag(Permissions.None)) // should be reported
{
}

if (permission.HasFlag(0)) // should also be reported
{
}

if (permission.HasFlag(Permissions.Read)) // should not be reported
{
}
}
}

```

**Documentation requirements:**

When this analyzer is implemented, it must be documented by following the steps at [Documentation for IDE CodeStyle analyzers](https://github.com/dotnet/roslyn/blob/main/docs/contributing/Documentation%20for%20IDE%20CodeStyle%20analyzers.md).

Contributor guide

Open the contributing guide

Research direction

The issue names no implementation files or tests. Start with the linked guidelines for new rules and the documentation for IDE CodeStyle analyzers, then identify the existing C# and VB analyzer entry points for Enum.HasFlag. Done means a documented warning for compile-time zero arguments, while unknown values and nonzero flags remain unreported.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp, visualbasic
Domain
compilers, tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.