1

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:

ContactNumberType is 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?

3 Answers 3

7

You have to use typeof becuase the GetNames() method takes a parameter of type Type. Keep in mind that providing a type name is not the same as an instance of Type, which is an object that contains the details of that type.

To pass a type as a parameter, you have two basic choices:

  • Pass a Type instance
  • Use a generic

The first of these (which many older methods such as Enum.GetNames() does) requires you to get a Type instance from the type identifier, which we can do using the typeof() 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):

var items = someList.OfType<SomeTypeName>();

Enum, however, doesn't have a generic form of GetNames() that allows this, though you could create something like one:

public static class EnumHelper
{
    public static string[] GetNames<T>() where T : struct
    {
        return Enum.GetNames(typeof(T))
    }
}

Which you could then call like:

string[] names = EnumHelper.GetNames<ContactNumberType>();
Sign up to request clarification or add additional context in comments.

Comments

2

GetNames takes a parameter of type Type. The issue is that ContactNumberType is not a Type object. When you use the typeof operator, it returns the appropriate Type object.

Comments

0

Because typeof operator returns an object of Type

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.