1

In MoreLinq project's source, I've seen this code :

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
        Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
    {
        if (source == null) throw new ArgumentNullException(nameof(source));
        if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));

        return _(); IEnumerable<TSource> _()
        {
            var knownKeys = new HashSet<TKey>(comparer);
            foreach (var element in source)
            {
                if (knownKeys.Add(keySelector(element)))
                    yield return element;
            }
        }
    }

I never saw such return construction. What does the _() means and how to use it ?

As I can't name this block, I didn't found any reference.

Steve B
  • 36,818
  • 21
  • 101
  • 174
  • 2
    I think the formatting/indentation has thrown you off, here. They're returning the result of the method named `_` (badly named). `_` is a local function, which is why it appears inside this method. Local functions were introduced in C# 7 so, relatively, new(ish). –  Oct 30 '18 at 09:29
  • The code is **exactly** this one. Check the linked page. And it compiles with no problem (VS 2017) – Steve B Oct 30 '18 at 09:31
  • @himbrombeere: thanks for the duplicate. Its answer is very comprehensive – Steve B Oct 30 '18 at 09:32
  • 2
    It really looks odd. If i'd use local functions i'd declare them before the `return`. And if i'd give them names like `_` and use them only once, i'd ask myself why i use them at all. – Tim Schmelter Oct 30 '18 at 09:32
  • As an aside, if anybody can shed some light on this choice of style - please share. It looks all off to me. –  Oct 30 '18 at 09:33
  • 2
    It's interesting that Jon skeet wrote this unreadable code. – Selman Genç Oct 30 '18 at 09:33
  • @SelmanGenç - he didn't. Annotate it, it was not Jon Skeet –  Oct 30 '18 at 09:35
  • 1
    @JᴀʏMᴇᴇ oh I see, nevermind. – Selman Genç Oct 30 '18 at 09:37

1 Answers1

1

It is simply a method named _, for example:

public int _()
{
     //some code here
}
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
  • While there *is* a method named `_`, it isn´t publicly available, but just defined locally **within** `DistinctBy`. – MakePeaceGreatAgain Oct 30 '18 at 09:46
  • @HimBromBeere well I don't deny it, i can see that there is a locally defined method..., but what would you answer `What does _() means?`? I said that its just a method with a name `_`, although it looks odd or unfamiliar, but its a valid method name. – Ashkan Mobayen Khiabani Oct 30 '18 at 09:51
  • understanding that `_` is indeed a variable or function name is part of the answer. That is is meant to mean 'so unimportant that it doesn't deserve a meaningful name' is another part..And understanding local functions should wrap it all up., – TaW Oct 30 '18 at 10:04