Skip to main content

Flaggen by Ricardo Boss

NuGet / site data

Nuget GitHub last commit GitHub Repo stars

Details

Info

info

Name: Flaggen

Package Description

Author: Ricardo Boss

NuGet: https://www.nuget.org/packages/Flaggen/

You can find more details at https://github.com/ricardoboss/Flaggen

Source: https://github.com/ricardoboss/Flaggen

Original Readme

note

Flaggen

A C# source generator that generates extension methods for flags enums.

Usage

Install the package:

dotnet add package Flaggen

Suppose we have this enum:

using System;

[Flags]
public enum LovelyColors {
RoseGold = 1 << 0,
SeaGreen = 1 << 1,
SunshineYellow = 1 << 2,
BrightRed = 1 << 3,
}

The source generator will notice the [Flags] attribute and generate extension methods for this enum:

// initalize with some value
var myColors = LovelyColors.RoseGold | LovelyColors.SeaGreen;

// manipulate the flags
myColors.Add(LovelyColors.BrightRed);
myColors.Remove(LovelyColors.RoseGold);
myColors.Toggle(LovelyColors.SeaGreen);

// check for flags
if (myColors.Has(LovelyColors.SunshineYellow))
Console.WriteLine("So shiny!");

All the extension methods using bitwise operators (so no reflection!), which makes them pretty fast (I will not prove this, but you get my trust-me-bro™️ guarantee).

License

MIT

About

note

Explicit operations about flags with enums, and bitwise operations

How to use

Example (source csproj, source files)

This is the CSharp Project that references Flaggen

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Flaggen" Version="1.1.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>

Generated Files

Those are taken from $(BaseIntermediateOutputPath)\GX

using System;

namespace EnumDemo
{
public static class ColorsFlaggenExtensions
{
public static void Add(ref this Colors value, Colors flag)
{
value |= flag;
}

public static void Remove(ref this Colors value, Colors flag)
{
value &= ~flag;
}

public static void Toggle(ref this Colors value, Colors flag)
{
value ^= flag;
}

public static bool Has(ref this Colors value, Colors flag)
{
return (value & flag) == flag;
}
}
}

Useful

Download Example (.NET C#)

Share Flaggen

https://ignatandrei.github.io/RSCG_Examples/v2/docs/Flaggen

In the same category (Enum) - 7 other generators

CredFetoEnum

EnumClass

EnumUtilities

FusionReactor

jos.enumeration

NetEscapades.EnumGenerators

PMart.Enumeration