What is the purpose of the two parentheses and arrow
service.GetDeviceLOV = () =>
I have been trying to figure out its function. Down below is the whole method which was used for unit testing. Hope this help give it context.
//A test for GetDeviceTypes
[TestMethod()]
[HostType("Moles")]
public void GetDeviceTypesTest()
{
SetUpMoles();
Login ();
service.GetDeviceLOV = () =>
{
return new List<DeviceLOV>() {
new DeviceLOV{DeviceType = "Type 1"},
new DeviceLOV{DeviceType = "Type 2"},
new DeviceLOV {DeviceType = "Type 1"}
};
};
List<string> actual;
actual = presenter.GetDeviceTypes();
Assert.AreEqual(2, actual.Count ,"actual.Count Should = 2");
}
This is a lambda expression and is used to create delegate to an anonymous function.
In your case, the GetDeviceLOV
property is a delegate which returns a List<DeviceLOV>
(or some interface this implements, such as IEnumerable<DeviceLOV>
).
The lambda expression allows you to write a "method" inline and create a delegate from it, and assign it to that property. Without this syntax, you'd need to create a separate method, and assign a delegate directly, ie:
private List<DeviceLOV> MakeDeviceList()
{
return new List<DeviceLOV>
{
new DeviceLOV{DeviceType = "Type 1"},
new DeviceLOV{DeviceType = "Type 2"},
new DeviceLOV {DeviceType = "Type 1"}
};
};
Then you'd write something like :
service.GetDeviceLOV = new Func<List<DeviceLOV>>(this.MakeDeviceList);
The lambda expression allows you to write the method "inline", and assign it directly. It also provides additional functionality (which isn't being used in this case) in that it allows you to reference local variables (which the compiler will turn into a closure), etc.
That is a lambda function with no arguments (an anonymous delegate). The curly braces and all the code in them on the following lines are part of that lambda also.
It is a way to create an anonymous method.
Basically, it is giving the GetDeviceLOV
method a body of:
{
return new List<DeviceLOV>() {
new DeviceLOV{DeviceType = "Type 1"},
new DeviceLOV{DeviceType = "Type 2"},
new DeviceLOV {DeviceType = "Type 1"}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With