Sinthia V
Sinthia V

Reputation: 2093

How can I use a type as a function parameter in C# 4.0?

Visual Studio reports that "'PhoenixEngineTypes.BehaviorTypes' is a 'type' but is used like a 'variable'".

public void AddBehavior(BehaviorTypes type)
    {
        if (Enum.IsDefined(BehaviorTypes, type))
        {
        switch (type)
        {
            case BehaviorTypes.render:
            break;   
        }
    }

The definition of BehaviorTypes is:

[Flags]
enum BehaviorTypes : uint
{
    default_behavior = 1 >> 0,
    select = 1 >> 1,
    render = 1 >> 2,
    animate = 1 >> 3,
    navigate = 1 >> 4,
    rotate = 1 >> 5,
    group = 1 >> 6,
    scale = 1 >> 7,
    collide = 1 >> 8,
    kill = 1 >> 9,
    attack = 1 >> 10,
    audio = 1 >> 11,
    all = UInt32.MaxValue
}

And finally:

public static bool IsDefined(Type enumType, object value);

Why can't I do this? I tried using typeof(type) and it compiles, but why waste a function call when the type is not variable? Shouldn't I be able to use the token directly?

Upvotes: 1

Views: 61

Answers (1)

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

You need to call IsDefined as follows

Enum.IsDefined(typeof(BehaviorTypes), type)

as it expects an instance of Type as input. BehaviorTypes is not an instance of Type, but you can get the corresponding Type instance for a type by using typeof.

See http://msdn.microsoft.com/en-us/library/system.enum.isdefined.aspx

Upvotes: 1

Related Questions