Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda