Simon
Simon

Reputation: 2035

lambda expression function

I have this code:

int pictureId=10;
string cacheKey = string.Format(ModelCacheEventConsumer.PICTURE_URL_MODEL_KEY, pictureId);
        return _cacheManager.Get(cacheKey, () =>
        {
            var url = _pictureService.GetPictureUrl(pictureId, showDefaultPicture: false);
            //little hack here. nulls aren't cacheable so set it to ""
            if (url == null)
                url = "";

            return url;
        });

What exactly this part of code means:"

() =>
{"
   var url =...."

Does it mean that function, which returns URL, is executed for every row from cache? What is then return type - list?

URL of documentation of this syntax?

Upvotes: 1

Views: 327

Answers (3)

GregC
GregC

Reputation: 8007

Second parameter to _cacheManager.Get() method is an anonymous method that captures pictureId and among other things.

https://msdn.microsoft.com/en-us/library/bb397687.aspx

C# Lambda expressions: Why should I use them?

To figure out the returned type, try using var keyword and creating a local variable: instead of return _cacheManager.Get() write var x = _cacheManager.Get() followed by return x. Then simply hover over the keyword var in Visual Studio.

Upvotes: 4

Andrew
Andrew

Reputation: 1534

What exactly this part of code means:

Well, lambda expression is a "shortcut" for delegate, and delegate is a reference to a callback function (in a very simple explanation). So this is a function which will be called inside your Get method of cache manager, which expects to have a Func delegate as a second param

Does it mean that function, which returns URL, is executed for every row from cache?

I think it will executes for row which has a key value the same as the value of cacheKey variable.. So, only one time (if keys are unique)

What is then return type - list?

The return type is string, because if result of GetPictureUrl is null it returns empty string. And calling this method is expecting to have a string in a result also

Upvotes: 1

fabriciorissetto
fabriciorissetto

Reputation: 10063

What exactly this part of code means

It's just passing a method by parameter.

Does it mean that function, which returns URL, is executed for every row from cache?

Only the content of the method Get of the object _cacheManager can answer this.

What is then return type - list?

The return type is a string, since your variable url is a string.

Upvotes: 1

Related Questions