Nifty .NET Part #2: Enumerable.Empty<T>

In part 2 the generic method Enumerable.Empty<T>, as the name would say it returns a empty IEnumerable of T:

public static IEnumerable<TResult> Empty<TResult>()

Lets see how it looks in code, for example we create a method that can return a list of strings:

   1:  using System;
   2:  using System.Linq;
   3:  using System.Collections.Generic;
   4:   
   5:  public class MyClass
   6:  {
   7:      public static void Main()
   8:      {
   9:          IEnumerable<string> names = GetNames(true);
  10:              
  11:          foreach(string name in names)
  12:          {
  13:              Console.WriteLine(name);    
  14:          }
  15:              
  16:          Console.ReadLine();
  17:      }
  18:      
  19:      public static IEnumerable<string> GetNames(bool condition)
  20:      {        
  21:          if(condition)
  22:          {
  23:              return new string[] { "Tom", "Robin", "Paul", "Dennis" };
  24:          }
  25:          
  26:          return Enumerable.Empty<string>();
  27:      }
  28:  }

So if condition is true the GetNames method will return an array of names, if not return an empty sequence of strings.

So why not return a string array of size 0 (new string[0]), well if we use Enumerable.Empty is more clearly what we want to do and every empty sequence of T will be cached so there is also some performance improvements.

The MSDN page of Enumerable.Empty<T>:

5 Comments

Comments have been disabled for this content.