" Can someone please tell me what is happening in the lower code in plain English, especially around characters =>a...">

Syntax refinement using "=>"

Can someone please tell me what is happening in the lower code in plain English, especially around characters =>and +=:

var ls = new LibraryServiceClient(AppSettings.Get("LibraryServiceBaseAddress"), 
                                  SessionId, App.Id, _user.UUID);
ls.MakingRequest += (s, e) =>
{
    LogStash.LogDebug("Library Service | Before making request  : {0}",
    DateTime.UtcNow.ToString("HH:mm:ss.fff"));
};
+4
source share
3 answers
(s,e) => { /*expresion*/ }

- lambda function.

This is a type Action<object, EventArgs>.

ls.MakingRequest

- event.

With +=you register the handler of this event. When the event is fired, all registered handlers will be executed.

The handler has the same signature as the action - it accepts the sender objectand EventArgseventArgs and returns void. Thus, the type of lambda function is compatible, so it will be called when the event fires.

+6

:

ls.MakingRequest +=

-, , , s e:

 (s, e) =>

-:

{ LogStash.LogDebug("Library Service | Before making request  : {0}", DateTime.UtcNow.ToString("HH:mm:ss.fff"));
+7

It is syntactic sugar to make chained extension methods more readable.

Below code will explain its evolution:

public class Program
{
    public void Main(string[] args)
    {
        // named delegate
        Tasker t = new Tasker();
        t.doer += DoProvider.DoThis;
        t.CallDoer("I am doing something");

        // anonymous method
        Tasker t2 = new Tasker();
        t2.doer += delegate(string s){
            Console.WriteLine (s);
        };
        t2.CallDoer("I am doing something again");

        // syntactical sugar over anonymous methods aka lambda expressions
        Tasker t3 = new Tasker();
        t3.doer += (s)=>{
            Console.WriteLine (s);
        };
        t3.CallDoer("I am doing yet another thing");
    }
}


public delegate void DoSomething(string Foo);

public class Tasker
{
    public event DoSomething doer;

    public void CallDoer(string s)
    {
        doer.Invoke(s);
    }
}

public static class DoProvider
{
    public static void DoThis(string Bar)
    {
        Console.WriteLine (Bar);
    }
}
+2
source

Source: https://habr.com/ru/post/1611384/


All Articles