Search code examples
c#listlinqenumerable

Is it necessary to use () with the Contains method?


I have code looking like this:

string target = ListOfTabs.FirstOrDefault(e.Target.Location.OriginalString.Contains);

I didn't write the code and I am trying to understand what it does. I saw there is a method called Contains() but cannot understand here why there are no () after the Contains. Is this a different thing? Can someone explain what this code is doing?

enter image description here


Solution

  • FirstOrDefault basically takes a function as argument. Writing

    ListOfTabs.FirstOrDefault(e.Target.Location.OriginalString.Contains);
    

    is practically the same as writing

    ListOfTabs.FirstOrDefault(x => e.Target.Location.OriginalString.Contains(x));
    

    Both Contains and x => Contains(x) are functions, so it works!