Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of using two blank parentheses followed by the arrow in c#

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");

    }
like image 302
Nik Avatar asked Apr 02 '13 18:04

Nik


3 Answers

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.

like image 152
Reed Copsey Avatar answered Nov 15 '22 00:11

Reed Copsey


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.

like image 41
Dylan Smith Avatar answered Nov 14 '22 23:11

Dylan Smith


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"}
}
like image 42
Jeff Vanzella Avatar answered Nov 15 '22 00:11

Jeff Vanzella