Implicit parameter specification with Lambdas

13 Feb

On the last line of code in the following code listing you will notice that the method of IList<T>.Add(T item) is called but with no parameter.

//our resulting output
IList<Person> lecturersEnrolledForStudy = new List<Person>();

//students and lecturers can enrol for study.
var newStudentEnrolementList = new List<Person>();

//filter the students out
var lecturersEnrollingInAClass = newStudentEnrolementList
                                    .Where(person => person.isLecturer)
                                    .ToList();

//add lecturers that are enrolling to the enrolled list.
lecturersEnrollingInAClass.ForEach(lecturersEnrolledForStudy.Add);

The parameter is still being populated like as if the following code was written:

lecturersEnrollingInAClass
            .ForEach(item => lecturersEnrolledForStudy.Add(item));

The parameter is inferred by the compiler just as the type of the “item” variable is by the lambda expression/list type. For those of us who are being weaned off traditional loops for these sorts of list interactions might find that it is more natural to think of the list that we are adding too first, and the list that the information is coming from second. This has reversed with lambdas.

A point worth making is that while this example I have provided is simple and could be done using an AddRange method, it is not as extensible and hence I suggest not using it. An example of the .ForEach extention methods extensibility would be that it can ‘addrange’s across different types and at different depths of objects. An example of this could be:

lecturersEnrollingInAClass
            .ForEach(item => lecturesNamesList.Add(item.Name));

In conclusion this is a handy shorthand to use with lambdas. If you already use the Resharper plug-in, this shorthand will have been suggested to you.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: