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?:
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));
}
}