This may be a basic question, but I googled it and didn’t find an answer. I hope you will help me. Consider I have an enum ContactNumberType:
string[] names = Enum.GetNames(typeof(ContactNumberType))
If I use the above, the compiler gives no error, but when I write:
string[] names = Enum.GetNames(ContactNumberType)
It says:
ContactNumberTypeis a type but used like a variable.
While the type of ContactNumberType is Enum, as far as I know, and the argument of method GetNames needs EnumType, so whats the issue with that?
You have to use
typeofbecuase the GetNames() method takes a parameter of typeType. Keep in mind that providing a type name is not the same as an instance ofType, which is an object that contains the details of that type.To pass a type as a parameter, you have two basic choices:
TypeinstanceThe first of these (which many older methods such as
Enum.GetNames()does) requires you to get aTypeinstance from the type identifier, which we can do using thetypeof()operator.The second of these allows you to pass a type name as a parameter to a method or class to make that method or class generic and tends to be used on newer methods (generics were introduced in .NET 2.0):
Enum, however, doesn’t have a generic form ofGetNames()that allows this, though you could create something like one:Which you could then call like: