Question

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.

Was it helpful?

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

OTHER TIPS

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();
}

You can cast it as it is being instantiated, then if it is used multiple times you won't need to recast it every time.

var view = (IView)Activator.CreateInstance(viewTypeMap[typeof(TView)]);
view.ShowDialog();

Change

(IView)view.ShowDialog();

to

((IView) view).ShowDialog();

Eric explained why

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top