views:

104

answers:

1

The MSDN magazine article by Josh Smith on MVVM contains a lambda expression I don't completely understand. What is the purpose of param in this code?

_saveCommand = new RelayCommand(param => this.Save(),
                param => this.CanSave );

Translated to my preferred language VB it's:

Dim saveAction as New Action(Of Object)(AddressOf Me.Save)
_saveCommand = New RelayCommand(saveAction, Function(param) Me.CanSave)

I would have expected to only see param if it is used within CanSave or Save. I am somewhat new to lambda expressions. It's odd for me to see a variable that is neither declared nor used anywhere as far as I can tell. Any explanation would be appreciated.

To put this in context the constructor for RelayCommand (C#) is:

public RelayCommand(Action<object> execute, Predicate<object> canExecute)

and in VB:

Public Sub New(ByVal execute As Action(Of Object), _
               ByVal canExecute As Predicate(Of Object))
+2  A: 

The lambda expression is declaring it - the place where it appears is basically a declaration. If it didn't, it wouldn't be compatible with Action(Of Object). That's why it's there - even though you don't actually need the value.

With anonymous methods, if you don't need any parameter values you can omit the parameter list entirely:

_saveCommand = new RelayCommand(delegate { this.Save(); },
     delegate { return this.CanSave; });

... but you can't do that with lambda expressions. You have to specify the parameter list - either just as a parameter name for a single parameter, or a full list in brackets. The code you've presented is equivalent to:

_saveCommand = new RelayCommand((Object param) => this.Save(),
     (Object param) => this.CanSave);
Jon Skeet
I think I get it now. But why is execute declared as Action(Of Object) when Object is ignored? Is it because RelayCommand Implements ICommand.Execute (which takes an object parameter)? Confusing stuff - I miss VB6!
DeveloperDan
@DeveloperDan: `RelayCommand` itself doesn't know whether or not you're going to ignore the parameter. It will *give* you the relevant value - it just so happens that these delegates are going to ignore it. Think of it as being like an event handler - not every event handler bothers using `sender` or `args`, do they? They just merrily ignore them, and all is well. It's exactly the same here.
Jon Skeet
DeveloperDan
@DeveloperDan: Glad it helped - and yes, I do tend to spew my thoughts fairly widely on the net :)
Jon Skeet
I found a helpful post at: http://community.visual-basic.it/alessandroenglish/archive/2010/06/25/29800.aspx It says "...notice that the param argument in methods is never used but it is required by the interface's signatures."
DeveloperDan