1

I've been away from C# for a while and now that I'm trying to read some code, I'm having a hard time find the meaning of it:

var server = new WebSocketServer("ws://localhost:8181");
server.Start(socket =>
{
    socket.OnOpen = () =>
    {
        Console.WriteLine("Open!");
        allSockets.Add(socket);
    };
    socket.OnClose = () =>
    {
        Console.WriteLine("Close!");
        allSockets.Remove(socket);
    };
    socket.OnMessage = message =>
    {
        Console.WriteLine(message);
        allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
    };
});

What's the name for socket => { .. } syntax and where can I find some text on it? And in which version of C# is it introduced? Is the = () => { .. } the same?

Mehran
  • 15,593
  • 27
  • 122
  • 221

2 Answers2

4

It is a lambda expression, basically it is a shortcut for defining delegates, which are anonimous methods. It was introduced in C# 3 along with LINQ to make its use much simpler. Syntax is as follow:

parameters => body

Usually the compiler can infer in some way the type of the parameter, that's why you see only the names of the parameters.

BlackBear
  • 22,411
  • 10
  • 48
  • 86
  • 1
    Delegates are *references* to methods; they are not actually methods. A delegate can reference a normal method or an anonymous method. A lambda expression is an anonymous method, though. – Matthew Watson Feb 09 '13 at 12:43
  • @MatthewWatson lambdas are references as well, I just wanted to keep my answer simple – BlackBear Feb 09 '13 at 12:47
  • Er, not they aren't - they are methods, but you can create a delegate to store a reference to them. http://msdn.microsoft.com/en-gb/library/bb397687.aspx – Matthew Watson Feb 09 '13 at 13:12
1

in c# this syntax is called Lambda Expressions. They are available since C# 3.0

more about:

Microsoft's Programming Guide explaining lambda expression

C# Lambda expressions: Why should I use them?

and an example of programmersheaven.com

Community
  • 1
  • 1
duffy356
  • 3,678
  • 3
  • 32
  • 47