Search code examples
c#linqresharpermethod-group

C# LINQ - Does Select filter nulls when used with a method group?


Today I wrote some code that takes a list of class A instances and creates a list of class B instances using a static factory method:

public abstract class B
{
    public static B CreateB(A a)
    {
        // return a new B instance or null if a B instance can't be created
    }
}

I needed to filter out the nulls so I used LINQ to do both tasks:

var bList = aList.Select(a => B.CreateB(a)).Where(b => b != null).ToList();

Code runs like expected, but I noticed Resharper was suggesting, on the call to CreateB, I should "Convert to method group". I wondered what that means and found some interesting answers on this site. For example: What is a method group in C#? and a comment by Asad to stitty's answer here Filtering Null values in Select (.Select(x => transform(x)) can be .Select(transform))

So I changed my code to:

var bList = aList.Select(B.CreateB).Where(b => b != null).ToList();

This too works as expected, but now I get to my question. Resharper now tells me the Where lambda expression can be removed because b != null "is always true".

I played around and Resharper is correct, but why? Why is there a difference in the returned collection of the Select() when I use a method group? Why does the Select() seem to filter out the nulls out of the collection when I use a method group?


Solution

  • Both aList.Select(a => B.CreateB(a)).Where(b => b != null).ToList(); and aList.Select(B.CreateB).Where(b => b != null).ToList(); use the same overload of Select method.

    I tested it with LinqPad and got the following output:

    LinqPad

    So Select doesn't filter anything. What version of Resharper and VisualStudio are you using?

    Latest ReSharper on VS2013 doesn't tell anything:

    Latest ReSharper on VS2013