What is the purpose of this C# syntax which appears to be using anonymous functions and javascript style property setting

StackOverflow https://stackoverflow.com/questions/7826838

  •  27-10-2019
  •  | 
  •  

Question

This is from Orchard CMS codegen. I do not understand and how the code below is not throwing syntax errors. Mainly, [parameter]:[Object] as well as the use of () => [an anonymous function perhaps]

return ContentShape("Parts_Product",
                () => shapeHelper.Parts_Product(
                    Sku: part.Sku,
                    Price: part.Price));
Was it helpful?

Solution

You're right about the first part; the () => ... represents an anonymous function that takes no arguments.

The second part you're confused about is known as named arguments. It's just like any other function call, except the code is explicitly stating which argument belongs to which parameter.

OTHER TIPS

Sku and Price are named parameters and () => is lambda expression. Moreover probably shapeHelper is dynamic type.

The second parameter is an anonymous, parameterless function that returns the result of the shapeHelper.Parts_Product method. The mapping hash passed as parameters allow specification of parameter values without passing them in the order designated by the prototype.

The twist here is that the shape helper is a dynamic object that decides dynamically what to do with the function call you make on it. In this case, there is no Part_Product method, it's being handled dynamically. Clay, the framework underneath this, is interpreting this as the creation of a shape called Part_Product and with the properties specified by the named parameters that are provided to the method. Essentially, this hijacks C# syntax for dynamic methods and named method parameters to build dynamic objects. To give you a point of comparison, the equivalent code in Javascript would look something like:

return function() {
    return {
        Part_Product: {
            Sku: part.Sku,
            Price: part.Price
        }
    };
};
() => shapeHelper.Parts_Product(
                    Sku: part.Sku,
                    Price: part.Price)

Is an anonymous delegate declared using a Lambda Expression.

It's a parameterless anonymous function. It just calls another method using named arguments. It comes handy when you have complicated signatures like:

private void DoSomething(string param1, string param2="param2default", string param3);

It may be hard to remember parameter order here and some of parameters may be optional and you may want to use those values. So when calling function you state explicitly those parameter names like this:

DoSomething(param1:"x", param3:"y");

Optional parameters and named arguments came out with C# 4.0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top