CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Mar 2011
    Posts
    9

    Lambda expressions

    Hi there. This is a general C# question about lambda expressions. I've read the chapter in my book about it (Schildt's C# 4.0) and there is one use of it that I run into online that the book does not cover and that I do not understand.

    Here are a couple of examples:

    EnqueueCallback(() => Assert.AreNotEqual(viewModel.Products, null,
    "Expected non-null products list."));

    Delete = new DeleteCommand(
    Service,
    ()=>CanDelete,
    contact =>
    {
    CurrentContact = null;
    Service.GetContacts(_PopulateContacts);
    });

    So the bit I don't understand is the notation with the empty brackets ( ()=> ). What is this all about? Can someone explain it please?

  2. #2
    Join Date
    Jan 2006
    Location
    Fox Lake, IL
    Posts
    15,007

    Re: Lambda expressions

    Delete is the LAMBDA which contains the actual code that fires when the ASSERT is TRUE (not NULL). It won't delete a record that isn't there
    David

    CodeGuru Article: Bound Controls are Evil-VB6
    2013 Samples: MS CODE Samples

    CodeGuru Reviewer
    2006 Dell CSP
    2006, 2007 & 2008 MVP Visual Basic
    If your question has been answered satisfactorily, and it has been helpful, then, please, Rate this Post!

  3. #3
    Join Date
    Mar 2011
    Posts
    9

    Re: Lambda expressions

    I guess I didn't make myself clear with what I wished to know. Those examples aren't what I'm interested in, it's specifically the '()=>'. I don't really get what it is.

  4. #4
    Join Date
    Oct 2005
    Location
    Seattle, WA U.S.A.
    Posts
    353

    Re: Lambda expressions

    The => operator indicates to the compiler that this is a lambda expression.

    The empty parentheses to the left of the operator indicates that this lambda expression takes no arguments, while everything to the right of the operator is the body of the expression.

    The body of the expression could be a call to a named function or it could be a bracketed series of one or more statements, to wit: {x++; return x * x;}

    incidentally, I think that the braces {} may be omitted if there is only a single statment in the body, for instance () => parser.ParseThis(HTML_string); (although for the life of me, I can't imagine why anyone would use a single-statement lambda expression - perhaps as an argument to a function or to subscribe to an event - like a delegate).
    Last edited by ThermoSight; March 24th, 2011 at 07:32 PM.

  5. #5
    Join Date
    Mar 2011
    Posts
    9

    Re: Lambda expressions

    Hmm I see. Nice answer - thanks a lot.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured