Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 417
Sergio Avatar asked Jan 29 '13 17:01

Sergio


2 Answers

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

like image 129
Eric Lippert Avatar answered Nov 03 '22 14:11

Eric Lippert


Why not try the following so that your view object is declared as IView instead of object?

public void ShowView<TView>(ViewModelBase viewModel, bool showDialog = false) where TView : IView
{
    var view = (IView)Activator.CreateInstance(viewTypeMap[typeof(TView)]);
    view.ShowDialog();
}
like image 2
Timothy G Avatar answered Nov 03 '22 14:11

Timothy G