Guy new to C# here. I was looking around MSDN skimming through enum
methods, but I could not tell the difference between TEnum
and enumType
.
public static bool TryParse<TEnum>(
string value,
out TEnum result)
public static string[] GetNames(
Type enumType)
What is the difference here? For the first method, wouldn't it possibly be better to return enumType result
instead?
TEnum is the Generic type of enumeration. You can pass any of your enumeration to that method. The second method is a non-generic one, where you would use a typeof keyword to identify the enums and return the enum names as a string collection.
If value is the string representation of the name of an enumeration value, the comparison of value with enumeration names is case-sensitive. If value is a name that does not correspond to a named constant of TEnum , the method returns false .
Enum. IsDefined is a check used to determine whether the values exist in the enumeration before they are used in your code. This method returns a bool value, where a true indicates that the enumeration value is defined in this enumeration and false indicates that it is not.
What is Enum in C#? C# enum is a value type with a set of related named constants often referred as an enumerator list. The C# enum keyword is used to declare an enumeration. It is a primitive data type, which is user-defined.
TEnum is the Generic type of enumeration. You can pass any of your enumeration to that method.
The second method is a non-generic one, where you would use a typeof keyword to identify the enums and return the enum names as a string collection
In TryParse<TEnum>()
is a generic method and TEnum
is the generic type parameter. Any time you see a method, class, or interface declaration followed by a name in angle brackets you have a generic type. Generics are used to provide compile time type checks and improve performance by specifying the type the method is to use.
GetNames
takes a Type object. A particular Type object represents particular class, interface, or enum. It's probably better to compare to Enum.Parse:
public static Object Parse(
Type enumType,
string value
);
Notice that Enum.Parse
returns an object
, which will require a cast to TEnum
.
Generics where not added until .Net 2.0 so you will see a number of methods that have a generic version and a generic version that takes a Type
object. The non-generic versions are also useful when working with reflection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With