Search code examples
c#genericsactivator

Cannot perform explicit cast


Can you clarify me why in this piece of code:

private Dictionary<Type, Type> viewTypeMap = new Dictionary<Type, Type>();

public void ShowView<TView>(ViewModelBase viewModel, bool showDialog = false)
    where TView : IView
{
    var view = Activator.CreateInstance(viewTypeMap[typeof(TView)]);
    (IView)view.ShowDialog();
}

I get the error:

"Only assignment, call, increment, decrement, and new object expressions can be used as a statement."

IView defines the ShowDialog() method.


Solution

  • The cast operator is of lower precedence than the member access operator.

    (A)B.C();
    

    is parsed as

    (A)(B.C());
    

    which is not a legal statement. You ought to write

    ((A)B).C();
    

    if you mean to cast B to A and then call C() on type A.

    For your future reference, the precedence table is here:

    http://msdn.microsoft.com/en-us/library/aa691323(v=VS.71).aspx