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

前端 未结 6 856
伪装坚强ぢ
伪装坚强ぢ 2020-12-23 02:22

Suppose you have a class Person :

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


        
6条回答
  •  萌比男神i
    2020-12-23 03:16

    Assuming you actually want to populate the Roles property somehow, then encapsulate that by making it's setter private and initialising it to a new list in the constructor:

    public class Person
    {
        public string Name { get; set; }
        public IList Roles { get; private set; }
    
        public Person()
        {
            Roles = new List();
        }
    }
    

    If you really really want to have the public setter, leave Roles with a value of null and avoid the object allocation.

提交回复
热议问题