jwillmer
jwillmer

Reputation: 3790

Can someone explain what´s happend in this codesnippet?

I´m working with ASP.NET MVC and went through some code and the syntax below is new for me. Could someone explain me how it works?

ViewDataInfo vdi = viewData.GetViewDataInfo(expression);
Func<object> modelAccessor = null;

modelAccessor = () => vdi.Value;

Upvotes: 2

Views: 263

Answers (2)

Oded
Oded

Reputation: 498942

This line sets the ViewDataInfo to the vdi variable:

ViewDataInfo vdi = viewData.GetViewDataInfo(expression);

This line initializes a null Func<object> delegate variable:

Func<object> modelAccessor = null;

This line sets the Func to a lambda expression that returns the value of vdi:

modelAccessor = () => vdi.Value;

Where the code below stands for an anonymous function that takes no parameter and returns an object (as specified in the generic type of the Func declaration):

() => vdi.Value

Upvotes: 1

Sergey Metlov
Sergey Metlov

Reputation: 26291

ViewDataInfo vdi = viewData.GetViewDataInfo(expression);

Getting the result of the GetViewDataInfo method, called with parameter expression.

Func<object> modelAccessor = null;
modelAccessor = () => vdi.Value;

Creating and initializing the delegate (function pointer) in view of lambda function. When in future code you make a call modelAccessor(), it'll return vdi.Value.

() - this means the function retrieve no parameters.
Func<object> - the function will return an object.
vdi.Value - is the short variant of { return vdi.Value; }

Read more about the lambda-functions.

Upvotes: 4

Related Questions