Can the type of a variable be determined by another variable?

P

pinkfloydfan

Hi there

I have the following situation...I want to perform an operation on an
Enum parameter but I don't know which one of a number of Enums it will
be on.

The function would include something like the following:

public static object (string EnumName)
{
....
EnumName NewEnum = new EnumName();
return NewEnum;

}

So, what I am trying to do is to create an instance of the specific
Enum whose name is held by the string EnumName. I am doing this
because exactly the same operation is being performed on all the Enums
and I just thought it would be neater to have it in a single function.

Is this possible?
Would object be the right return type given that I now want to use
NewEnum in another function that is looking for that specific variable
type?
I am very new to C# so if anyone can help it would be appreciated.

Thanks a lot
 
N

Nicholas Paldino [.NET/C# MVP]

What is in EnumName (it should be "enumName", btw, according to the
public naming guidelines)? Is it the name of the value in the enumeration,
or the name of the type itself? I imagine it is the name of a value, and
the type of the enumeration (like Day.Sunday).

You might want to split this up into two parameters, enumType and value,
both of strings. The first will be the type name, which you can use to pass
to the static GetType method on the Type class to get a Type instance
representing the enumeration.

Once you have that, you can call the static Parse method on the Enum
class to get the value of the enum.

And yes, object is what you want to return, since enumerations can use
different underlying value types (int, short, byte).

In the end, you will have something like this:

public static object (string enumType, string value)
{
// Get the type of the enumeration.
Type t = Type.GetType(enumType);

// Get the value.
return Enum.Parse(t, value);
}
 
L

Lew

pinkfloydfan said:
So, what I am trying to do is to create an instance of the specific
Enum whose name is held by the string EnumName. I am doing this
because exactly the same operation is being performed on all the Enums
and I just thought it would be neater to have it in a single function.

Couldn't you write that method genericized on the Enum type?

That would give you type safety and none of reflection's hazards.
 
P

pinkfloydfan

I'm sorry Lew, I am rather new to c#/.net programming (all I have
known in the past is VBA) and haven't got a clue what you mean by
genericized or reflection.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top