50

I was trying to enable SSL in my C# client program and found the following code in this answer:

System.Net.ServicePointManager.ServerCertificateValidationCallback +=
    (se, cert, chain, sslerror) =>
    {
        return true;
    };

I added the code to my program and it solved the problem, but I completely don't get how exactly it works.

The left part System.Net.ServicePointManager.ServerCertificateValidationCallback is some callback and += modifies that callback. But what does the remaining construct mean? I spent 20 minutes searching to at least find how it is properly called and where I can find more info on how to read that, but all in vain. I suppose it is somehow related to LINQ and searched for "LINQ arrow", but didn't find anything reasonable.

How is that (blah,blah,blah)=>{return true;} construct called and where can I find more info on such constructs?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
sharptooth
  • 167,383
  • 100
  • 513
  • 979

7 Answers7

103

That is a lambda expression. It is a very special anonymous delegate. Basically you are defining a method and not giving a name. Its parameters are to the left of the => and the method body is to the right of the =>. In your particular case,

(se, cert, chain, sslerror) => { return true; };

is an anonymous method defined by a lambda expression. This particular method has four parameters

object se
X509Certificate cert
X509Chain chain
SslPolicyErrors sslerror

and the method body is

return true;

It's as if you had said

class ServerCertificateValidation {
    public bool OnRemoteCertificateValidation(
        object se,
        X509Certificate cert,
        X509Chain chain,
        SslPolicyErrors sslerror
    ) {
        return true;
    }
}

and then

var validation = new ServerCertificateValidation();
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
    validation.OnRemoteCertificateValidation;

How is that (blah,blah,blah)=>{return true;} construct called and where can I find more info on such constructs?

It's called the same way that any other method is called. For example, you can do this:

Func<int, int, int> adder = (m, n) => m + n;

Here I am defining a method that eats a pair of int and returns an int. That int is obtained by adding the values of the input parameters. It can be invoked like any other method.

int four = adder(2, 2); 

Here's an article on MSDN on lambda expressions and an article on the lambda operator. If you're really interested, the name comes from lambda calculus.

surfmuggle
  • 5,527
  • 7
  • 48
  • 77
jason
  • 236,483
  • 35
  • 423
  • 525
  • Besides of the syntax I want to know is this sort of implementation (returning true value for all cases) does not lead to a security bug? I mean we should do some validation and this sort of returning true for all cases makes our code prone to security-risks. – VSB Feb 12 '18 at 08:58
  • 1
    It seems this sort of implementation is a security risk and this case is noted in the answer of main question [over here](https://stackoverflow.com/a/1742967/1080355) – VSB Feb 12 '18 at 09:02
  • I like reading your messages in SO @jason thanks – Soner from The Ottoman Empire Apr 19 '21 at 19:56
  • What about the question marks in this line of code? `public IRepository GuiaRepository => _guiaRepository ?? (_guiaRepository = new Repository(_context));` I mean, the `??`. – carloswm85 Apr 26 '22 at 13:13
  • Please do not WRITE codes encoding methods or functions like that. It is unreadable and hard to maintain later. :) – TomeeNS Aug 17 '22 at 04:43
23

For completeness (for search results, etc): in more recent versions of C# (since 6.0), the => syntax has been extended from just lambdas for delegates and expression trees, to cover expression-bodied members. This means that a range of simple members such as properties, methods, etc - can be implemented as expression bodies; for example:

public int Foo { get { return innerObj.SomeProp; } }
public void Bar() { Write("Thing"); }

can be written:

public int Foo => innerObj.SomeProp;
public void Bar() => Write("Thing");
geekley
  • 1,231
  • 10
  • 27
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
11

The =>-Operator represents a lambda expression.

But for those of you who visit the question nowadays, another use-case might be the arrow as a shorthand for a property getter. This feature got introduced in C# 6. So instead of writing

public string Foo
{
    get
    {
        return this.bar;
    }
}

you can use following snippet:

public string Foo 
{
    get => this.bar;
}

or even shorter:

public string Foo => this.bar;
ˈvɔlə
  • 9,204
  • 10
  • 63
  • 89
6

It's called a lambda expression.

http://msdn.microsoft.com/en-us/library/bb311046.aspx - The lambda operator.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
4
(blah,blah,blah)=>{return true;} 

is a lambda expression. It doesn't look like the lambdas you're used to because it doesn't use any arguments which get passed to it. The compiler will turn this lambda into a delegate function for you, without you having to go through the long, annoying process of creating a whole function which implements the delegate specification that ServicePointManager.ServerCertificateValidationCallback uses.

Dave Markle
  • 95,573
  • 20
  • 147
  • 170
4

Jason explains it very well. Here is an example using an event that is listened to using different techniques:

using System;

namespace Events
{
   class Program
    {
        static void Main(string[] args)
        {
            Events e = new Events();
            e.FireEvents();
            Console.ReadLine();
        }
    }

    public class Events
    {
        private event EventHandler<EventArgs> EventTest;

        public Events()
        {
            EventTest += new EventHandler<EventArgs>(function);

            EventTest += delegate
            {
                Console.WriteLine("written by an anonymous method.");
            };

            EventTest += (o, e) =>
            {
                Console.WriteLine("written by a lambda expression");
            };
        }

        private void function(object sender, EventArgs e)
        {
            Console.WriteLine("written by a function.");
        }

        public void FireEvents()
        {
            if (EventTest != null)
                EventTest(this, new EventArgs()); 
        }
    }
}
miyamotogL
  • 513
  • 3
  • 10
1

This snippet is called anonymous function. It builds an anonymous method around the callback delegate and allways returns true.

MacX
  • 587
  • 5
  • 16