App
App

Reputation: 356

How does a lambda expression working in the given code snippet

I have the below code snippet in my project. I am new to lambda expressions. I have some idea about it and also started using it. But I do not understand how the below code is working. Specially,

NotifyIntrenal( notification, callback, changedTypes => ..

Now here changedTypes is one of the parameter for method NotifyIntrenal. We derive its value using an anomymous method.

If I see the code, since I do not assign any value to changedTypes, so as per my understanding the code if (changedTypes == null) should always be true. But this is not the case when I debug.

Can someone explain me how does this works here?

private void Notify( Notification notification )
{
    var nameDto = GetNameDto();
    foreach (var subscription in _subscriptionsDictionary)
    {
        var callback = subscription.Key;
        var subscribedTypes = subscription.Value;
        NotifyIntrenal( notification, callback, changedTypes =>
            {
                if (changedTypes == null)
                    return subscribedTypes;

                if (!changedTypes.Any())
                    return subscribedTypes;

                return changedTypes.Intersect(subscribedTypes);
             }, nameDto);
    }
}

Thanks & Regards

Upvotes: 0

Views: 144

Answers (2)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

changedTypes is just a paremeter for your anonymous method, not for NotifyIntrenal. The latter however calls that anonymous method and fills the parameter (if required) appropriately. In your case the anonymous method expects an IEnumerable<MyType> and returns an IEnumerable<MyType>.

NotifyIntrenal(string arg1, string arg2, Func<IEnumerable<MyType>, IEnumerable<MyType>> func) {
    // do something

    var list = new List<MyType> { ...}
    // execute the delegate with the list
    IEnumerable<MyType> result = func(list);
}

So actually changedTypes is provided by NotifyIntrenal, not given to it. How you create that argument within the method is up to you.

Upvotes: 0

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43876

changedTypes is not an argument to NotifyInternal. It is the parameter for the anonymous method.
This whole method is the argument for NotifyInternal.

The code inside that lambda is not executed at this point. It will only be executed if some line in NotifyInternal calls it. So there has to be code line in NotifyInternal executing the anonymous method:

void NotifyInternal(Notification notification, Callback callback, Func<IEnumerable<Type>, IEnumerable<Type>> function, string nameDto)
{
    // ... some code

    // execute the lambda
    var result = function(mychangedtypesvariable);

    // ... more code
}

Only then the code inside the lambda is executed, using the pass argument (mychangedtypesvariable in that example). So if this will be null you cannot decide from the snippet you see.

Upvotes: 3

Related Questions