There's a fair bit of room for personal opinion here, but in general terms:
- Declaring and initializing the field on the same line helps you to verify the field is initialized without needing to look in multiple places. If you see a field declared without an initializer, you have to look in a different part of code to see whether the item is being initialized at all.
- There are circumstances (like when the initial value is based on a constructor argument) when you cannot initialize the field inline. Since you will sometimes need to initialize fields in the constructor, some people will argue that it's more consistent to always initialize them there.
You may also want to ask: Should I be requiring/allowing an initial value to be provided in the constructor?
class Book
{
readonly List<double> grades;
public Book() : this(Array.Empty<double>())
{
}
public Book(IEnumerable<double> grades)
{
this.grades = grades.ToList();
}
public void AddGrade(double grade)
{
grades.Add(grade);
}
}
And: should my class actually just be a dumb data container without a constructor or logic? (Is book.AddGrade(...)
really more sensible than book.Grades.Add(...)
?)
class Book
{
public List<double> Grades {get;} = new List<double>();
}