kurnakovv / EnumConverter

EnumConverter is a little open source library for converting enums
MIT License
9 stars 3 forks source link

ToEnumOrDefault #61

Closed kurnakovv closed 2 months ago

kurnakovv commented 5 months ago

ToEnumOrDefault

Description

Try convert string value to enum or return default value if not possible.

Signature

bool ToEnumOrDefault(this string, bool [default = true], TEnum [default = TEnum]) where TEnum : struct, Enum

Type Parameters

TEnum - Enum that we want try to get after convert.

Parameters

Returns TEnum or defaultValue if not possible to convert.

Code examples

public enum MyEnum { First, Second, Third }
string stringValueFirst = "First";
string stringValueSecond = "Second";
string stringValueInvalid = "Blablabla";

MyEnum enumFirst = stringValueFirst.ToEnumOrDefault<MyEnum>();
MyEnum enumSecond = stringValueSecond.ToEnumOrDefault<MyEnum>(false);
MyEnum enumThird = stringValueInvalid.ToEnumOrDefault<MyEnum>(MyEnum.Third);

// output
// enumFirst - MyEnum.First
// enumSecond - MyEnum.Second
// enumThird - MyEnum.Third
Kurnakova commented 4 months ago

Hi

Kurnakova commented 3 months ago

@kurnakovv Hey, why do we sometimes use TAnotherEnum and sometimes TEnum, what's the difference, why do we need two?

kurnakovv commented 3 months ago

@Kurnakova it depends on an input parameter TAnotherEnum - when you convert input enum to another enum TEnum - when you convert input string to enum In your cases you need to use TEnum, because input parameter is string (not enum)

I hope it's clear

P.S. Of course you can use TEnum for both cases, or just T, but I think my code is better

Kurnakova commented 3 months ago

@kurnakovv

Returns "TAnotherEnum" or "defaultValue" if not possible to convert.

Why does say that it returns TAnotherEnum though? Or is this a typo?

kurnakovv commented 3 months ago

Good catch, fixed

Kurnakova commented 3 months ago

@kurnakovv

Code Examples bool enumFirst = stringValueFirst.ToEnumOrDefault();

Why is it bool? Shouldn't it be "MyEnum" or smth like that, since this method returns enums?

kurnakovv commented 3 months ago

@Kurnakova yep, good catch, thank you! I fixed