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?
-
What type is _cacheManager?Clay Ver Valen– Clay Ver Valen2016年01月04日 19:59:53 +00:00Commented Jan 4, 2016 at 19:59
-
_cacheManager implements ICacheManager IDisposable interface, which has method Get defined as: T Get<T>(string key);Simon– Simon2016年01月04日 20:29:37 +00:00Commented Jan 4, 2016 at 20:29
3 Answers 3
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.
Comments
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.
2 Comments
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