Initialize class fields in constructor or at declaration?

前端 未结 15 2066
南旧
南旧 2020-11-22 01:16

I\'ve been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.

Should I do it at declaration?:



        
15条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 02:08

    There are many and various situations.

    I just need an empty list

    The situation is clear. I just need to prepare my list and prevent an exception from being thrown when someone adds an item to the list.

    public class CsvFile
    {
        private List lines = new List();
    
        public CsvFile()
        {
        }
    }
    

    I know the values

    I exactly know what values I want to have by default or I need to use some other logic.

    public class AdminTeam
    {
        private List usernames;
    
        public AdminTeam()
        {
             usernames = new List() {"usernameA", "usernameB"};
        }
    }
    

    or

    public class AdminTeam
    {
        private List usernames;
    
        public AdminTeam()
        {
             usernames = GetDefaultUsers(2);
        }
    }
    

    Empty list with possible values

    Sometimes I expect an empty list by default with a possibility of adding values through another constructor.

    public class AdminTeam
    {
        private List usernames = new List();
    
        public AdminTeam()
        {
        }
    
        public AdminTeam(List admins)
        {
             admins.ForEach(x => usernames.Add(x));
        }
    }
    

提交回复
热议问题