Today, I'd like to share with you some common extension methods related to enumeration operations.
We usually use the normal enumeration, but also have the bit-flag enumeration with the [Flags] feature, so all of the following extensions apply to both the normal enumeration and the bit-flag enumeration.
We first define two enumerations for the following extension methods to test the applicability of the code as follows:
//Normal enumeration
internal enum StatusEnum
{
[Description("Normal")]
Normal = 0,
[Description("Standby")]
Standby = 1, [Description("Normal")] Normal = 0, [Description("Standby")]
[Description("Offline")]
Offline = 2,
Online = 3, [Description("Offline")]
}
// Enumeration of bit flags
[Flags]
internal enum TypeFlagsEnum
{
[Description("Http Protocol")]
Http = 1, [Description("Http Protocol")]
[Description("Udp protocol")]
Udp = 2,
[Description("Http Protocol, Udp Protocol")]
HttpAndUdp = 3,.
[Description("Tcp Protocol")]
Tcp = 4,
}
01The enumeration is converted to an enumeration based on the name of the enumeration.
This method takes an enum name string and converts it to the corresponding enum, or null if the conversion fails.
It first checks if the string is an integer-valued string, and if it is, it returns null, because enumeration names cannot be integer-valued strings.
The TryParse method is then called to perform the conversion with the following code:
//Convert to an enumeration based on the name of the enumeration, if the conversion fails, return null.
public static T? ToEnumByName<T>(this string name) where T : struct, Enum
{
//If the integer type string, then directly return null
if ((name, out _))
{
return default;
}
// Return the result if the conversion is successful, otherwise return null.
if (<T>(name, out var result))
{
return result; }
}
return default; }
}
Below we have a detailed unit test, respectively, for normal enumeration and bit flag enumeration of the two cases, the specific use case is as follows:
(1) Normal enum name string, successfully converted to enum;
(2) A non-existent enum name string returns null;
(3) A string of integer type that returns null;
(4) Normal bit flag enum name string, successfully converted to enum;
(5) A non-existent bit flag enumeration name string returns null;
(6) Normal bit flag enum name combination string, successfully converted to enum;
(7) A non-existent bit flag enumeration name combination string returns null;
Bit flag enumeration name combination string refers to the combination of two enumeration items, which is also a bit flag enumeration characteristics, do not understand the bit flag enumeration can be on their own first to supplement the relevant knowledge.
The specific code is as follows:
[Fact]
public void ToEnumByName()
{
// Normal enumeration name string, successfully converted to enumeration
var status = "Standby".ToEnumByName<StatusEnum>(); ();
(, status);
// Returns null for non-existent enum name strings
var isStatusNull = "StandbyNull".ToEnumByName<StatusEnum>();
(isStatusNull);
// integer type string, return null
var isStatusNullInt = "3".ToEnumByName<StatusEnum>();
(isStatusNullInt);
// Normal bit flags enum name string, successfully converted to enumeration
var flags = "HttpAndUdp".ToEnumByName<TypeFlagsEnum>(); ();
(, flags);
// Non-existent bit flag enum name string, return null
var isFlagsNull = "HttpAndUdpNull".ToEnumByName<TypeFlagsEnum>(); ();
(isFlagsNull);
// Normal bit flags enum name combination string, successfully converted to enumeration
var flagsGroup = "Http,Tcp".ToEnumByName<TypeFlagsEnum> ();
( | , flagsGroup).
// Non-existent bit flag enumeration name combination string, return null
var isFlagsGroupNull = "Http,Tcp,Null".ToEnumByName<TypeFlagsEnum>();
(isFlagsGroupNull);
}
02The following are some examples of the enumerations that can be converted to enumerations or default values based on the enumeration name.
This method is complementary to the previous method and is used to handle the fact that if the conversion is unsuccessful, then a specified default enumeration value is returned, as described in the following code:
//Convert to an enumeration based on the name of the enumeration, if the conversion fails, the default enumeration will be returned.
public static T ToEnumOrDefaultByName<T>(this string name, T defaultValue) where T : struct, Enum
{
// Call the method that converts the enumeration to an enumeration based on its name.
var result = <T>();
if ()
{
return ;
}
// If the conversion fails, return the default value
return defaultValue; }
}
Because the method calls the previous method, so we will simply test, conversion success returns the correct value, conversion failure returns the default value, the specific code is as follows:
[Fact]
public void ToEnumOrDefaultByName()
{
// Normal enum name string, successfully converted to enumeration
var status = "Standby".ToEnumOrDefaultByName();
(, status);
// non-existent enum name string, return the specified default value
var statusDefault = "StandbyNull".ToEnumOrDefaultByName();
(, statusDefault);
}
03The enumerations are converted to enumerations based on the enumeration descriptions.
This method receives the enumeration description string and converts it to the corresponding enumeration, and returns null if the conversion fails, in which if the enumeration item has no description it is replaced by the enumeration name, the specific code is as follows:
//Convert to an enumeration based on the enumeration description and return null if the conversion fails.
public static T? ToEnumByDesc<T>(this string description) where T : struct, Enum
{
// First get all the items of the enumeration
foreach (Enum value in (typeof(T)))
{
//Take the description of the enumeration item and compare it to the description of the target, if it's the same, then return the enumeration item.
if (() == description)
{
return (T)value;
}
}
// Returns the default value if no match is found for the description
return default; }
}
One of the ToEnumDesc methods is explained in more detail below.
We unit test the method for the following five scenarios:
(1) Normal enum description string, successfully converted to enum;
(2) If the enumeration item does not have an enumeration description, the enumeration name string, successfully converted to an enumeration;
(3) A non-existent enum description string returns null;
(4) Normal bit flag enumeration description string, successfully converted to enumeration;
(5) A non-existent bit flag enumeration describes the string conversion and returns null;
The specific code is as follows:
[Fact]
public void ToEnumByDescription()
{
// Normal enumeration description string, successfully converted to enumeration
var status = "Standby".ToEnumByDesc<StatusEnum>();
(, status);
// If the enumeration item does not have an enumeration description, then enumerate the name string, successfully converted to an enumeration
var statusNotDesc = "Online".ToEnumByDesc<StatusEnum>();
(, statusNotDesc);
// Non-existent enum description string, return null
var isStatusNull = "StandbyNot".ToEnumByDesc<StatusEnum>();;
(isStatusNull);
// Normal bit flags enum description string, successfully converted to enumeration
var flags = "Http Protocol, Udp Protocol".ToEnumByDesc<TypeFlagsEnum>();;
(, flags);
// Non-existent bit flag enumeration describes string conversion, returns null
var isFlagsNull = "Http Protocol Udp Protocol".ToEnumByDesc<TypeFlagsEnum>();;
(isFlagsNull);
}
04, converted to enumeration or default value based on enumeration description
This method is complementary to the previous method and is used to handle the fact that if the conversion is unsuccessful, then a specified default enumeration value is returned, where if the enumeration item is not described it is replaced by the enumeration name, as described in the following code:
//Convert to enumeration based on enumeration description, fail to return to default enumeration.
public static T? ToEnumOrDefaultByDesc<T>(this string description, T defaultValue) where T : struct, Enum
{
// Call the method to convert to an enumeration based on the enumeration description.
var result = <T>();
if ()
{
return ;
}
// Return the default value if no match is found.
return defaultValue; }
}
Again we perform simple unit tests:
[Fact]
public void ToEnumOrDefaultByDesc()
{
// Normal enum description string, successfully converted to an enumeration
var status = "standby".ToEnumOrDefaultByDesc();
(, status);
// Non-existent enum description string, return the specified default value
var statusDefault = "Standby None".ToEnumOrDefaultByDesc();
(, statusDefault);
}
05The enumerations are converted to enumeration values based on the enumeration name.
This method receives the enumeration name string and converts it to the corresponding enumeration value, and returns null if the conversion fails, the specific code is as follows:
//Convert to an enum value based on the name of the enum, if conversion fails, return null.
public static int? ToEnumValueByName<T>(this string name) where T : struct, Enum
EnumValueByName
// Call the EnumValueByName method.
var result = <T>();
if ()
{
return Convert.ToInt32();
}
// If the conversion fails, return null
return default; }
}
We do detailed unit testing for the following five scenarios:
(1) Normal enum name string, successfully converted to enum value;
(2) A non-existent enum name string returns null;
(3) Normal bit flag enum name string, successfully converted to enum value;
(4) Normal bit flag enumeration name combination string, successfully converted to enumeration value;
(5) A non-existent bit flag enumeration Int value conversion returns null;
The specific code is as follows:
[Fact]
public void ToEnumValueByName()
{
// Normal enum name string, successfully converted to enum value
var status = "Standby".ToEnumValueByName<StatusEnum>();
(1, status);
// Returns null for non-existent enum name strings.
var isStatusNull = "StandbyNull".ToEnumValueByName<StatusEnum>();
(isStatusNull);
// Normal bit flags enum name string, successfully converted to enum value
var flags = "HttpAndUdp".ToEnumValueByName<TypeFlagsEnum>(); ();
(3, flags);
// Normal bit flags enum name combination string, successfully converted to enum value
var flagsGroup = "Http,Udp".ToEnumValueByName<TypeFlagsEnum>(); ();
(3, flagsGroup);
// non-existent bit flag enum name string, return null
var isFlagsNull = "HttpUdp".ToEnumValueByName<TypeFlagsEnum>();
(isFlagsNull);
}
06The following are some examples of the enumerations that can be converted to enumeration values or default values based on the name of the enumeration.
This method is complementary to the previous method and is used to handle the fact that if the conversion is unsuccessful, then a specified default enumeration value is returned, as described in the following code:
//Convert to an enum value based on the name of the enum, if the conversion fails, the default enum value is returned.
public static int ToEnumValueOrDefaultByName<T>(this string name, int defaultValue) where T : struct, Enum
{
// Convert to enum value based on enum name.
var result = <T>();
if ()
{
return ;
}
// If the conversion fails, return the default value
return defaultValue; }
}
We perform a simple unit test with the following code:
[Fact]
public void ToEnumValueOrDefaultByName()
{
// Normal enum name string, successfully converted to enum value
var status = "Standby".ToEnumValueOrDefaultByName<StatusEnum>(2);
(1, status);
// non-existent enum name string, return the specified default value
var statusDefault = "StandbyNull".ToEnumValueOrDefaultByName<StatusEnum>(2);
(2, statusDefault);
}
07The enumeration name is converted to an enumeration description.
This method receives the enumeration name string and converts it to the corresponding enumeration description, and returns null if the conversion fails, in which if the enumeration item does not have a description it is replaced by the enumeration name, the specific code is as follows:
//Convert to enum description based on enum name, return null if conversion fails.
public static string? ToEnumDescByName<T>(this string name) where T : struct, Enum
{
// Call the EnumDescByName method.
var result = <T>();
if ()
{
//convert to enum description
return ();
}
// Return null if conversion fails
return default; }
}
Because the method is all internal calls to existing methods, so do a simple unit test, the specific code is as follows:
[Fact]
public void ToEnumDescByName()
{
// Normal bit flags enum name string, successfully converted to enum description
var flags = "HttpAndUdp".ToEnumDescByName<TypeFlagsEnum>();
("HttpProtocol,UdpProtocol", flags);;
// Normal bit flags enum name combination string, combination item exists, successfully converted to enum description
var flagsGroup = "Http,Udp".ToEnumDescByName<TypeFlagsEnum>();
("Http Protocol,Udp Protocol", flagsGroup);;
// Normal bit flags enum name combination string, combination item does not exist, successfully converted to enum description
var flagsGroup1 = "Http,Tcp".ToEnumDescByName<TypeFlagsEnum> ();
("Http protocol, Tcp protocol", flagsGroup1);
}
08The enumerations are converted to enumeration descriptions or default values based on the enumeration name.
This method is complementary to the previous method and is used to handle the fact that if the conversion is unsuccessful, then a description of the specified default enumeration is returned, as described in the following code:
//Convert to enum description based on the name of the enum, if conversion fails, return the default enum description.
public static string ToEnumDescOrDefaultByName<T>(this string name, string defaultValue) where T : struct, Enum
{
// Call the EnumDescOrDefaultByName method.
var result = <T>();
if (! (result))
{
return result; }
}
// If the conversion fails, return the default enumeration description.
return defaultValue; }
}
Do a simple unit test, the specific code is as follows:
[Fact]
public void ToEnumDescOrDefaultByName()
{
// Normal enum name string, successfully converted to enum description.
var status = "Standby".ToEnumDescOrDefaultByName<StatusEnum>("Testing");
("standby", status);.
// non-existent enum name string, return the specified default enum description
var statusDefault = "StandbyNull".ToEnumDescOrDefaultByName<StatusEnum>("Test");;
("Test", statusDefault);
}
Later on I will upload the library to Nuget so you can use it directly.
classifier for sums of money: The test method code as well as the sample source code have been uploaded to the code repository for those who are interested./hugogoos/Ideal