Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
Why is better to use a local function instead of just inlining the code?

I've found this code in here:

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;
        }
    }
}

At first I didn't understand this part return _(); IEnumerable<TSource> _(), but I realized that it's a local function called and declared in the same line. It was done here.

My question is: is there any advantage over simply inlining that 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));
    var knownKeys = new HashSet<TKey>(comparer);
    foreach (var element in source)
    {
        if (knownKeys.Add(keySelector(element)))
            yield return element;
    }
}

I'd say the current version is more verbose and has more indentation, so what is the advantage? Is just a matter of taste?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The version with the local method will throw immediately if source or keySelector is null, because it's not implemented with an iterator block.

The "inlined" version uses an iterator block, so none of the code - including the validation - will execute until the calling code starts to iterate over the returned IEnumerable<TSource>.

In general, eager validation makes it easier to spot and understand errors: the stack trace is clearer, and there's no delay between "making the broken call" and "seeing the failure".

The same approach can also be used to write task-returning methods that fail eagerly: write a "regular" task-returning method that calls an async local method after performing validation.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda