michael.bartnett
michael.bartnett

Reputation: 777

Why does RelayCommand<T>.Execute take an object instead of a T?

This hasn't done anything but cause the need for what would otherwise be unnecessary casting (or rather, caused me to pull down the codebase and make the change myself). Is there a reason for doing this?

References:

Source on Codeplex

Blog posting with source

Edit Here's an example:

DoCommand = new RelayCommand<AsyncCallback>((callBack) =>
{
    Console.WriteLine("In the Action<AsyncCallback>");
    SomeAsyncFunction((async_result) =>
    {
        Console.WriteLine("In the AsyncCallback");
        callBack.Invoke(new MyAsyncResult(true));
    });
});

DoCommand.Execute((iasyncresult) => Console.WriteLine(iasyncresult.IsCompleted));
//Where MyAsyncResult is a class implement IAsyncResult that sets IsCompleted in the constructor
// This will cause the "cannot cast lambda as object" error

Upvotes: 2

Views: 977

Answers (2)

user7116
user7116

Reputation: 64148

Your error is due to the lambda not being able to be passed as an object. Instead try:

AsyncCallback callback = (iasyncresult) => Console.WriteLine(iasyncresult.IsCompleted);
DoCommand.Execute(callback);

Upvotes: 1

user1228
user1228

Reputation:

Because ICommand is not generic. A generic implementation of ICommand must cast from the interface, handle invalid casts, and forward the cast instance to the generic methods.

Upvotes: 6

Related Questions