Search code examples
c#wpfenumsprism

Why can I not use as-cast to convert `object` to an enum type?


When you implement ICommand you have to implement the public void Execute(object parameters) method, which takes parameters of type object.

For my specific application I'm interested in how I can implement an ICommand which takes an enum as parameter.

In my command I implement Execute like this:

public void Execute(object parameter)
{
  if (parameter is null) throw new ArgumentNullException("parameter");
  State s = parameter as State;
  }

where State is my enum type defined as

public enum State
{
  NeutralState,
  MeasureCircleState,
  MeasureSphereState  
}

Unfortunately my IDE flags my code, specifically the line State s = parameter as State; as invalid.

What is wrong with my code?
Can I not convert my object parameter to my enum type State?


Solution

  • object parameter can be converted to enum:

    public void Execute(object parameter)
    {
        if (parameter is State s)
        {
           // do work;
        }
        else
        {
             throw new ArgumentException(nameof(parameter));
        }
    }
    

    you should also pass it correctly from XAML, e.g:

    CommandParameter="{x:Static local:State.NeutralState}"
    

    and not just CommandParameter="NeutralState", which will pass a string