GithubHelp home page GithubHelp logo

engrajabi / enum.source.generator Goto Github PK

View Code? Open in Web Editor NEW
174.0 7.0 14.0 423 KB

A C# source generator to create an enumeration class from an enum type. With this package, you can work on enums very, very fast without using reflection.

License: MIT License

C# 98.66% Batchfile 1.34%
codegeneration csharp-sourcegenerator fast-enum codegenerator enums enum-generator source-generator source-generators enum-fast enumgenerator

enum.source.generator's Introduction

GitHub license Nuget Nuget

Supernova.Enum.Generators

The best Source Generator for working with enums in C#

A C# source generator to create an enumeration class from an enum type. With this package, you can work on enums very, very fast without using reflection.

Package - Supernova.Enum.Generators

Add the package to your application using

dotnet add package Supernova.Enum.Generators

Adding the package will automatically add a marker attribute, [EnumGenerator], to your project.

To use the generator, add the [EnumGenerator] attribute to an enum. For example:

[EnumGenerator]
public enum UserTypeTest
{
    [Display(Name = "مرد", Description = "Descمرد")] Men = 3,

    [Display(Name = "زن", Description = "Descزن")] Women = 4,

    //[Display(Name = "نامشخص")]
    None
}

This will generate a class called EnumNameEnumExtensions (UserTypeTest + EnumExtensions), which contains a number of helper methods. For example:

    /// <summary>
    /// Provides extension methods for operations related to the <see cref="global::UnitTests.UserTypeTest" /> enumeration.
    /// </summary>    
    [GeneratedCodeAttribute("Supernova.Enum.Generators", null)]
    public static class UserTypeTestEnumExtensions
    {
        /// <summary>
        /// Provides a dictionary that maps <see cref="global::UnitTests.UserTypeTest" /> values to their corresponding display names.
        /// </summary>
        public static readonly ImmutableDictionary<UnitTests.UserTypeTest, string> DisplayNamesDictionary = new Dictionary<UnitTests.UserTypeTest, string>
        {
                {UnitTests.UserTypeTest.Men, "مرد"},
                {UnitTests.UserTypeTest.Women, "زن"},
                {UnitTests.UserTypeTest.None, "None"},

        }.ToImmutableDictionary();

        /// <summary>
        /// Provides a dictionary that maps <see cref="global::UnitTests.UserTypeTest" /> values to their corresponding descriptions.
        /// </summary>
        public static readonly ImmutableDictionary<UnitTests.UserTypeTest, string> DisplayDescriptionsDictionary = new Dictionary<UnitTests.UserTypeTest, string>
        {
                {UnitTests.UserTypeTest.Men, "Descمرد"},
                {UnitTests.UserTypeTest.Women, "Descزن"},
                {UnitTests.UserTypeTest.None, "None"},

        }.ToImmutableDictionary();

        /// <summary>
        /// Converts the <see cref="global::UnitTests.UserTypeTest" /> enumeration value to its string representation.
        /// </summary>
        /// <param name="states">The <see cref="global::UnitTests.UserTypeTest" /> enumeration value.</param>
        /// <param name="defaultValue">The default value to return if the enumeration value is not recognized.</param>
        /// <returns>The string representation of the <see cref="global::UnitTests.UserTypeTest" /> value.</returns>
        public static string ToStringFast(this UnitTests.UserTypeTest states, string defaultValue = null)
        {
            return states switch
            {
                UnitTests.UserTypeTest.Men => nameof(UnitTests.UserTypeTest.Men),
                UnitTests.UserTypeTest.Women => nameof(UnitTests.UserTypeTest.Women),
                UnitTests.UserTypeTest.None => nameof(UnitTests.UserTypeTest.None),
                _ => defaultValue ?? throw new ArgumentOutOfRangeException(nameof(states), states, null)
            };
        }

        /// <summary>
        /// Checks if the specified <see cref="global::UnitTests.UserTypeTest" /> value is defined.
        /// </summary>
        /// <param name="states">The <see cref="global::UnitTests.UserTypeTest" /> value to check.</param>
        /// <returns>True if the <see cref="global::UnitTests.UserTypeTest" /> value is defined; otherwise, false.</returns>
        public static bool IsDefinedFast(UnitTests.UserTypeTest states)
        {
            return states switch
            {
                UnitTests.UserTypeTest.Men => true,
                UnitTests.UserTypeTest.Women => true,
                UnitTests.UserTypeTest.None => true,
                _ => false
            };
        }

        /// <summary>
        /// Checks if the specified string represents a defined <see cref="global::UnitTests.UserTypeTest" /> value.
        /// </summary>
        /// <param name="states">The string representing a <see cref="global::UnitTests.UserTypeTest" /> value.</param>
        /// <returns>True if the string represents a defined <see cref="global::UnitTests.UserTypeTest" /> value; otherwise, false.</returns>
        public static bool IsDefinedFast(string states)
        {
            return states switch
            {
                nameof(UnitTests.UserTypeTest.Men) => true,
                nameof(UnitTests.UserTypeTest.Women) => true,
                nameof(UnitTests.UserTypeTest.None) => true,
                _ => false
            };
        }

        /// <summary>
        /// Converts the <see cref="global::UnitTests.UserTypeTest" /> enumeration value to its display string.
        /// </summary>
        /// <param name="states">The <see cref="global::UnitTests.UserTypeTest" /> enumeration value.</param>
        /// <param name="defaultValue">The default value to return if the enumeration value is not recognized.</param>
        /// <returns>The display string of the <see cref="global::UnitTests.UserTypeTest" /> value.</returns>
        public static string ToDisplayFast(this UnitTests.UserTypeTest states, string defaultValue = null)
        {
            return states switch
            {
                UnitTests.UserTypeTest.Men => "مرد",
                UnitTests.UserTypeTest.Women => "زن",
                UnitTests.UserTypeTest.None => "None",
                _ => defaultValue ?? throw new ArgumentOutOfRangeException(nameof(states), states, null)
            };
        }

        /// <summary>
        /// Gets the description of the <see cref="global::UnitTests.UserTypeTest" /> enumeration value.
        /// </summary>
        /// <param name="states">The <see cref="global::UnitTests.UserTypeTest" /> enumeration value.</param>
        /// <param name="defaultValue">The default value to return if the enumeration value is not recognized.</param>
        /// <returns>The description of the <see cref="global::UnitTests.UserTypeTest" /> value.</returns>
        public static string ToDescriptionFast(this UnitTests.UserTypeTest states, string defaultValue = null)
        {
            return states switch
            {
                UnitTests.UserTypeTest.Men => "Descمرد",
                UnitTests.UserTypeTest.Women => "Descزن",
                UnitTests.UserTypeTest.None => "None",
                _ => defaultValue ?? throw new ArgumentOutOfRangeException(nameof(states), states, null)
            };
        }

        /// <summary>
        /// Retrieves an array of all <see cref="global::UnitTests.UserTypeTest" /> enumeration values.
        /// </summary>
        /// <returns>An array containing all <see cref="global::UnitTests.UserTypeTest" /> enumeration values.</returns>
        public static UnitTests.UserTypeTest[] GetValuesFast()
        {
            return new[]
            {
                UnitTests.UserTypeTest.Men,
                UnitTests.UserTypeTest.Women,
                UnitTests.UserTypeTest.None,
            };
        }

        /// <summary>
        /// Retrieves an array of strings containing the names of all <see cref="global::UnitTests.UserTypeTest" /> enumeration values.
        /// </summary>
        /// <returns>An array of strings containing the names of all <see cref="global::UnitTests.UserTypeTest" /> enumeration values.</returns>
        public static string[] GetNamesFast()
        {
            return new[]
            {
                nameof(UnitTests.UserTypeTest.Men),
                nameof(UnitTests.UserTypeTest.Women),
                nameof(UnitTests.UserTypeTest.None),
            };
        }

        /// <summary>
        /// Gets the length of the <see cref="global::UnitTests.UserTypeTest" /> enumeration.
        /// </summary>
        /// <returns>The length of the <see cref="global::UnitTests.UserTypeTest" /> enumeration.</returns>
        public static int GetLengthFast()
        {
            return 3;

        }

        /// <summary>
        /// Try parse a string to <see cref="global::UnitTests.UserTypeTest" /> value.
        /// </summary>
        /// <param name="states">The string representing a <see cref="global::UnitTests.UserTypeTest" /> value.</param>
        /// <param name="result">The enum <see cref="global::UnitTests.UserTypeTest" /> parse result.</param>
        /// <returns>True if the string is parsed successfully; otherwise, false.</returns>
        public static bool TryParseFast(string states, out UnitTests.UserTypeTest result)
        {
            switch (states)
            {
                case "Men": 
                {
                    result = UnitTests.UserTypeTest.Men;
                    return true;
                }
                case "Women": 
                {
                    result = UnitTests.UserTypeTest.Women;
                    return true;
                }
                case "None": 
                {
                    result = UnitTests.UserTypeTest.None;
                    return true;
                }
                default: {
                    result = default;
                    return false;
                }
            }
        }
    }

You do not see this file inside the project. But you can use it.

Usage

var stringEnum = UserTypeTest.Men.ToStringFast(); //Men;

var isDefined = UserTypeTestEnumExtensions.IsDefinedFast(UserType.Men); //true;

var displayEnum = UserTypeTest.Men.ToDisplayFast(); //مرد

var descriptionEnum = UserTypeTest.Men.ToDescriptionFast(); //Descمرد

var names = UserTypeTestEnumExtensions.GetNamesFast(); //string[]

var values = UserTypeTestEnumExtensions.GetValuesFast(); //UserType[]

var length = UserTypeTestEnumExtensions.GetLengthFast(); //3

var menString = "Men";
var result = UserTypeTestEnumExtensions.TryParseFast(menString, out var enumValue);

If you had trouble using UserTypeTestEnumExtensions and the IDE did not recognize it. This is an IDE problem and you need to restart the IDE once.

Benchmark

Benchmark

Contributing

Create an issue if you find a BUG or have a Suggestion or Question. If you want to develop this project :

  1. Fork it!
  2. Create your feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request

Give a Star! ⭐️

If you find this repository useful, please give it a star. Thanks!

License

Supernova.Enum.Generators is Copyright © 2022 Mohsen Rajabi under the MIT License.

enum.source.generator's People

Contributors

dameng324 avatar dependabot[bot] avatar engrajabi avatar ohflowi avatar samjib avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

enum.source.generator's Issues

Trying to use this to generate enums in more than one csproj

I would like to have enums generated in separate projects but i am getting this warning and cant seem to find the generated enums

warning CS0436: The type 'EnumGeneratorAttribute' in 'E:\ZiiDMSV2\V2\Client\Common\ReceiptPrinter\obj\Debug\net8.0\Supernova.Enum.Generators\Supernova.Enum.Generators.EnumSourceGenerator\EnumGeneratorAttribute.g.cs' conflicts with the imported type 'EnumGeneratorAttribute' in 'ZiiDMSApp.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'E:\ZiiDMSV2\V2\Client\Common\ReceiptPrinter\obj\Debug\net8.0\Supernova.Enum.Generators\Supernova.Enum.Generators.EnumSourceGenerator\EnumGeneratorAttribute.g.cs'.

Should returning false rather than throwing an exception be better behaviour?

The code looks very good, but I think it is more useful if 'IsDefinedFast(string states)' returns false rather than throwing an exception. This means that if the string is not defined in the enum collection and we get back 'false' and can act on that in the if statement.

Here is my example:

// currently throws an exception (would be better if it returned false)
if (UserTypeTestEnumExtensions.IsDefinedFast("Gien"))
{
    System.Console.WriteLine("'Gien' is defined");
}
else
{
    System.Console.WriteLine("Not defined is 'Gien'"); 
}


Here is the pseudo code for what I am suggesting:

public static bool IsDefinedFast(string states)
{
    return states switch
    {
        nameof(UnitTests.UserTypeTest.Men) => true,
        nameof(UnitTests.UserTypeTest.Women) => true,
        nameof(UnitTests.UserTypeTest.None) => true,
        _ => false
    };
}

This is only for this specific scenario that I suggest returning false.

What do you think?

Idea for a new feature

I think it may be useful to have the inverse of ToDisplayFast(), which I have called ToEnumFast(). Here is the pseudo code that should be generated.

public static UnitTests.UserTypeTest ToEnumFast(this string states)
    {
        return states switch
        {
            "مرد" => UnitTests.UserTypeTest.Men,
            "زن" => UnitTests.UserTypeTest.Women,
            "None" => UnitTests.UserTypeTest.None,
            _ => throw new ArgumentOutOfRangeException()
        };
    }

Do you like this idea?

Warning CS1591 : Missing XML comment for publicly visible type or member 'DirectionEnumExtensions'

my enum is public and I set

		<GenerateDocumentationFile>True</GenerateDocumentationFile>

then I got this compile warning:

0>Direction_EnumGenerator.g.cs(6,25): Warning CS1591 : Missing XML comment for publicly visible type or member 'DirectionEnumExtensions'
0>Direction_EnumGenerator.g.cs(8,95): Warning CS1591 : Missing XML comment for publicly visible type or member 'DirectionEnumExtensions.DisplayNamesDictionary'
0>Direction_EnumGenerator.g.cs(24,95): Warning CS1591 : Missing XML comment for publicly visible type or member 'DirectionEnumExtensions.DisplayDescriptionsDictionary'
0>Direction_EnumGenerator.g.cs(40,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'DirectionEnumExtensions.ToStringFast(Direction, string)'
0>Direction_EnumGenerator.g.cs(58,28): Warning CS1591 : Missing XML comment for publicly visible type or member 'DirectionEnumExtensions.IsDefinedFast(Direction)'
0>Direction_EnumGenerator.g.cs(76,28): Warning CS1591 : Missing XML comment for publicly visible type or member 'DirectionEnumExtensions.IsDefinedFast(string)'
0>Direction_EnumGenerator.g.cs(94,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'DirectionEnumExtensions.ToDisplayFast(Direction, string)'
0>Direction_EnumGenerator.g.cs(112,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'DirectionEnumExtensions.ToDescriptionFast(Direction, string)'
0>Direction_EnumGenerator.g.cs(130,59): Warning CS1591 : Missing XML comment for publicly visible type or member 'DirectionEnumExtensions.GetValuesFast()'
0>Direction_EnumGenerator.g.cs(147,32): Warning CS1591 : Missing XML comment for publicly visible type or member 'DirectionEnumExtensions.GetNamesFast()'
0>Direction_EnumGenerator.g.cs(164,27): Warning CS1591 : Missing XML comment for publicly visible type or member 'DirectionEnumExtensions.GetLengthFast()'

how can I solve this?

Dose not work with internal visibility

The generated code has errors, if the used enum has the visibility internal.

Inconsistent accessibility: parameter type ProjectItemType is less accessible than method ProjectItemTypeEnumExtensions.IsDefinedFast(ProjectItemType)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.