Mehran
Mehran

Reputation: 16861

Looking for the name of a C# syntax

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?

Upvotes: 1

Views: 77

Answers (2)

duffy356
duffy356

Reputation: 3718

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

Upvotes: 1

BlackBear
BlackBear

Reputation: 22979

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.

Upvotes: 4

Related Questions