Reputation: 16861
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
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
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