Lambda Expression

Ronald Rex 1,671 Reputation points
2023-08-10T19:13:21.1466667+00:00

Hi Friends. I have a method that uses a Lambda Expression that I needed clarity about. Does everyrthing on the left side of TestNetPayData go into the object? Why is the New keyword used so much, in this case 3 times.

public static IEnumerable<object[]> TestNetPayData =>

new List<object []>
{
  new object[]{ new CheckModel {_grosspay=500, _sswh=0, _mcwh=0, _netpay=12000},0}
}; 
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


Answer accepted by question author

P a u l 10,766 Reputation points
2023-08-10T19:39:36.5233333+00:00

On the left hand side of TestNetPayData you have IEnumerable<object[]>, which you can think of as the return type, similar to if you wrote this as a regular method:

public static IEnumerable<object[]> TestNetPayData() {
	return new List<object[]>
	{
		new object[]{ new CheckModel {_grosspay=500, _sswh=0, _mcwh=0, _netpay=12000},0}
	};
}

The reason you have 3 new keywords is because the object you're returning is a list, of arrays, of objects. The first new creates the the List<>, the second creates an object[] nested inside it, then finally a CheckModel inside that.

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 84,671 Reputation points
    2023-08-10T20:01:32.12+00:00

    the new operator is used to create an instance of a class object.

    looking at your property get expression (it not a lambda as closure and multi line are not supported).

    the property TestNetPayData, every time referenced return a new List of object arrays. this is a rather bad practice as property is typically expected to return the same object. I would have expected a GetTestNetPayData() method instead.

    anyway looking at the code expanded into separate lines (requires old get format)

    public static IEnumerable<object[]> TestNetPayData
    {
        get 
        {
            // create checkModel instance
            var checkModel = new CheckModel 
            {
                 _grosspay=500, 
                 _sswh=0, 
                 _mcwh=0, 
                 _netpay=12000
            };
            // create object array instance
            var objects = new object[] {checkModel};
    
            // create list instance
            var list = new List<object[]> { objects};
    
            // return list instance
            return list;
        }
    }
    

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.