What is this ReSharper snippet 'convert to method group' actually doing?
Asked Answered
N

2

8

enter image description here

Code before the changes:

List<ProductBrandModel> model = brands.Select(item => Mapper.Map<ProductBrand, ProductBrandModel>(item)).ToList();

Code after the improvement:

List<ProductBrandModel> model = brands.Select(Mapper.Map<ProductBrand, ProductBrandModel>).ToList();

What is this doing? Is it implicitly running that mapping on every item in the brands collection?

Nikko answered 24/8, 2011 at 20:55 Comment(1)
I also faced the same issue with my below code while understanding TPL: private static void ParallelForEach() { Parallel.Invoke(() => Method1(), () => Method2()); } private static void Method1() { //do some work } private static void Method2() { //do some work }Kaunas
S
10

Since you're directly passing the parameter of the lambda expression to the Mapper.Map method, it is exactly equivalent to specifying this method directly as the projection for Select. The signature of Mapper.Map is compatible with the Func<TSource, TResult> delegate, so R# suggests to use the method group directly rather than a lambda expression.

Stentorian answered 24/8, 2011 at 20:59 Comment(2)
You have three upvotes but I have more questions. :) I understand the signature is <TSource, TResult> but what is being projected when I use the improved code? Does the .Select burp up each ProductBrand object and Mapper.Map assumes that bit is the TSource?Nikko
Well, TSource is already known, since brands is a collection of ProductBrand. The compiler infers TResult from the return type of Mapper.Map.Stentorian
E
3

The first line creates a method that immediately calls the Mapper.Map function. This is unnecessary since the Mapper.Map method matches the expected definition of Select and can call Mapper.Map directly. Resharper changes it so that only 1 method is called and the extra method is not generated by the compiler.

Enjoyable answered 24/8, 2011 at 21:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.