0

In what scenario would you initialise class variables in constructors and when without constructor?

class CustomList
{
            public Node head;
            public int count;

    public CustomList()
    {
        head = foo;
        count = 1;
    }
}

Or

class CustomList
    {
        public Node head =foo;
        public int count =1;   
    }
Yugraaj Sandhu
  • 392
  • 3
  • 14
  • Some of the claims from the duplicates are outdated: you can initialize properties (though you use public fields, which you shouldn't) inline for quite some time already. – CodeCaster Apr 16 '23 at 14:03

1 Answers1

1

Neither is necessary. Objects will default to null, and integers to zero. Meaning, you could also have

class CustomList
{
  public Node head;
  public int count;
}

(But, I'd recommend making private fields with getters and setters)

In any case, defining a constructor is best practice. If you want a static constant, then you must define that at the class level, but that wouldn't be an instance variable as shown here.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • _"defining a constructor is best practice"_ - citation needed. And why do you recommend fields? Auto-implemented properties have been a sensible default for over a decade already. – CodeCaster Apr 16 '23 at 14:00
  • thanks .sorry for confusion. i mean if the values are no defauls such as count=2. or some other starting values. – Yugraaj Sandhu Apr 16 '23 at 15:00
  • Why not use constructor parameters, then? If you have an empty Linked list class, why start count at more than zero? In both examples you've changed, neither will compile with foo being undefined – OneCricketeer Apr 16 '23 at 15:01