Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between 'enumType' and 'TEnum'

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?

like image 790
Wasiim Ouro-sama Avatar asked Aug 09 '15 18:08

Wasiim Ouro-sama


People also ask

What is TEnum?

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.

Is enum TryParse case sensitive?

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 .

How do you check if an enum is valid?

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.

Is enum primitive type C#?

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.


2 Answers

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

like image 161
Karthik Avatar answered Oct 02 '22 17:10

Karthik


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.

like image 34
shf301 Avatar answered Oct 02 '22 17:10

shf301