Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for a default enum value? #508

Open
ChapterSevenSeeds opened this issue Mar 25, 2024 · 1 comment
Open

Support for a default enum value? #508

ChapterSevenSeeds opened this issue Mar 25, 2024 · 1 comment

Comments

@ChapterSevenSeeds
Copy link

@ardalis, I am wondering what your thoughts are regarding the idea of having the option of specifying a default enum value for a class inheriting from SmartEnum.

For example, let's say I have the following enum:

public class Status : SmartEnum<Status> 
{
    public static readonly Status Other = new(nameof(Pending), 0);
    public static readonly Status Pending = new(nameof(Pending), 1);
    public static readonly Status Completed = new(nameof(Completed), 2);

    private Status(string name, int value) : base(name, value) { }
}

Then, if I were to do this:

var status = Status.FromName("Cancelled");

An exception gets thrown. Instead, I would prefer to have the Other status returned if an unknown is specified in the FromName method. How would you recommend solving this? Would there be any benefit to adding a new constructor to SmartEnum that allows an enum to specify whether it is to be used as a default value?

@HAOYI99
Copy link

HAOYI99 commented Nov 22, 2024

my approach is to create my own parsing method

this is my smartenum

public static readonly JobResult FAILED = new("Failed", 0);
public static readonly JobResult ABORTED = new("Aborted", 1);
public static readonly JobResult FINISHED = new("Finished", 2);
public static readonly JobResult UNKNOWN = new("Unknown", 3);

and method to parse, if not found then return UNKNOWN

public static JobResult TryParse(string? result)
{
    return TryFromName(result, out var jobResult) ? jobResult : UNKNOWN;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants