Alex Rivera | Logout

Is it better to use Enumerable.Empty<T>() as opposed to new List<T>() to initialize an IEnumerable<T>?

Asked 2009-12-12T17:05:57.397
207

Suppose you have a class Person :

public class Person
{
   public string Name { get; set;}
   public IEnumerable<Role> Roles {get; set;}
}

I should obviously instantiate the Roles in the constructor. Now, I used to do it with a List like this :

public Person()
{
   Roles = new List<Role>();
}

But I discovered this static method in the System.Linq namespace

IEnumerable<T> Enumerable.Empty<T>();

From MSDN:

The Empty(TResult)() method caches an empty sequence of type TResult. When the object it returns is enumerated, it yields no elements.

In some cases, this method is useful for passing an empty sequence to a user-defined method that takes an IEnumerable(T). It can also be used to generate a neutral element for methods such as Union. See the Example section for an example of this use of

So is it better to write the constructor like that? Do you use it? Why? or if not, Why not?

public Person()
{
   Roles = Enumerable.Empty<Role>();
}
Edit
Report

1 Answer

7

The typical problem with exposing the private List as an IEnumerable is that the client of your class can mess with it by casting. This code would work:

  var p = new Person();
  List<Role> roles = p.Roles as List<Role>;
  roles.Add(Role.Admin);

You can avoid this by implementing an iterator:

public IEnumerable<Role> Roles {
  get {
    foreach (var role in mRoles)
      yield return role;
  }
}
answered 2009-12-12T17:46:49.630

Your Answer