tags:

views:

369

answers:

4

I'd like to declare an "empty" lambda expression that does, well, nothing. Is there a way to do something like this without needing the DoNothing() method?

    public MyViewModel()
    {
        SomeMenuCommand = new RelayCommand(
                x => DoNothing(),
                x => CanSomeMenuCommandExecute());
    }

    private void DoNothing()
    {
    }

    private bool CanSomeMenuCommandExecute()
    {
        // this depends on my mood
    }

My intent in doing this is only control the enabled/disabled state of my WPF command, but that's an aside. Maybe it's just too early in the morning for me, but I imagine there must be a way to just declare the x => DoNothing() lambda expression in some way like this to accomplish the same thing:

    SomeMenuCommand = new RelayCommand(
        x => (),
        x => CanSomeMenuCommandExecute());

Is there some way to do this? It just seems unnecessary to need a do-nothing method.

+4  A: 

Assuming you only need a delegate (rather than an expression tree) then this should work:

SomeMenuCommand = new RelayCommand(
        x => {},
        x => CanSomeMenuCommandExecute());

(That won't work with expression trees as it's got a statement body. See section 4.6 of the C# 3.0 spec for more details.)

Jon Skeet
+6  A: 

This should work:

SomeMenuCommand = new RelayCommand(
    x => {},
    x => CanSomeMenuCommandExecute());
Joseph
+17  A: 
Action doNothing = () => { };
Rauhotz
Perfect! Thanks!
unforgiven3
A: 

I don't fully understand why do you need a DoNothing method.

Can't you just do:

SomeMenuCommand = new RelayCommand(
                null,
                x => CanSomeMenuCommandExecute());
Jorge Córdoba
That is probably checked and will probably throw a NRE.
Dykam
I think Dykam is right, but I just didn't think about passing null :-)
unforgiven3