1

I've read about static. I know that it's a prefix that is accessible only by non-objects. But I can't understand why Easter has to be static?

class JsonFile
{
    public List<Holiday> StandardHolidays = new List<Holiday>();
    public List<ChangingHoliday> ChangingHoliday = new List<ChangingHoliday>();

    public static Easter Easter = new Easter();
    public static DaysToOffset GoodFriday = new DaysToOffset("Good Friday", Easter, -2);
}

I don't get the concept of static yet. Can someone please explain?

Idos
  • 15,053
  • 14
  • 60
  • 75
Code_Steel
  • 437
  • 2
  • 8
  • 14
  • 2
    Where is `static`? – Kenneth K. Apr 18 '16 at 19:58
  • To achieve this, move initialization into an explicit non-static constructor, like this: `class JsonFile { public List StandardHolidays; public List ChangingHolidays; public Easter Easter; public DaysToOffset GoodFriday; public JsonFile() { StandardHolidays = new List(); ChangingHolidays = new List(); Easter = new Easter(); GoodFriday = new DaysToOffset("Good Friday", Easter, -2); }` If you have several constructor overloads defined, do not forget to "chain" the `: this()` constructor from everywhere. – Jeppe Stig Nielsen Apr 18 '16 at 20:40

1 Answers1

3

During initialization you cannot have an instance of Easter but you require one when you use

public DaysToOffset GoodFriday = new DaysToOffset("Good Friday", Easter, -2);

so Easter has to be static in order that its existence in GoodFriday would be valid.

Idos
  • 15,053
  • 14
  • 60
  • 75
  • Can you explain why I cannot have an instance of Easter? – Code_Steel Apr 18 '16 at 20:05
  • He can work around that by moving the initialization of the fields (or even just the fourth of them) into a non-static constructor. – Jeppe Stig Nielsen Apr 18 '16 at 20:06
  • @Code_Steel Because the compiler can rearrange these - there is no guarantee that `Easter` will be initialized before `GoodFriday`, so without using `static` you might have gotten a `NullReferenceException`. Read the duplicate question it has a great explanation by Oded. – Idos Apr 18 '16 at 20:06
  • @Idos OP explains why in the answer. – paparazzo Apr 18 '16 at 20:09
  • The explanation mentioned (in your comment) is incorrect. I added a comment in the linked thread, under Oded's answer there. – Jeppe Stig Nielsen Apr 18 '16 at 20:20