jsmars
jsmars

Reputation: 1928

Do anonymous initializes override defaults, or are they run after?

If I have a default initializer set, and a define an anonymous one when I create my object. Is the default skipped, or just run before? The reason I want to know is because in the case below, if they are run after, the List object created in the default will be discarded immediately, thus creating unnecessary garbage.

class ArrangedPanel : RectElement
{
    public List<RectElement> arrangedChildren = new List<RectElement>();
    public int Padding = 2;
}

//Somewhere else
new ArrangedPanel() 
{ 
   Padding = 5,
   arrangedChildren = new List<RectElement>()
   {
      new ButtonToggle(),
      new ButtonToggle()
   }
}

Upvotes: 1

Views: 132

Answers (3)

Andrew Marshall
Andrew Marshall

Reputation: 1569

From the C# Specification, section 17.4.5.2

The instance field variable initializers of a class correspond to a sequence of assignments that are executed immediately upon entry to any one of the instance constructors (§17.10.2) of that class. The variable initializers are executed in the textual order in which they appear in the class declaration. The class instance creation and initialization process is described further in §17.10.

Thus the initializations in the body class declaration will be performed first, followed by the initializations in the constructor. This can be observed directly by viewing the IL output.

Upvotes: 1

Frederiek
Frederiek

Reputation: 1613

arrangedChildren will be set to the last instance you create

for example:

arrangedChildren = new List<RectElement>();
arrangedChildren = new List<RectElement>()
   {
      new ButtonToggle(),
      new ButtonToggle()
   }

the arrangedChildren will point to the second list. If no other object references to the first one it will disapair (GC). But if some 1 would keep a reference to the first instance it will stay alive and you could have duplicates or two differents lists where you are working on.

This could cause some problems

Upvotes: 1

Enigmativity
Enigmativity

Reputation: 117144

In your example code the Padding = 2 occurs before Padding = 5.

You are unnecessarily creating a List<RectElement>, but I'd challenge you to create a scenario where such unnecessary allocations cause any appreciable performance hit.

Upvotes: 2

Related Questions