Initialize Objects Properly: Listing 1: C#, Display the Initialization Order

This code shows a marker class that displays a message when it's created, and a test class that creates an object of multiple types. The marker class helps keep track of when a field is initialized. The BaseTrackType creates a set of marker objects so that you can determine when an object is initialized.

public class Marker
{
   private readonly string objectName;

   public Marker(string label)
   {
      objectName = label;
      Console.WriteLine("{0} was created", objectName);
   }
}

public class BaseTrackType
{
   private static Marker staticInit = 
     new Marker("statically initialized");
   private static Marker staticInit2 =
     new Marker("statically2 initialized");

   private static Marker staticCtor;

   static BaseTrackType()
   {
     staticCtor = 
       new Marker("Static Ctor initialized");
   }

   private Marker fieldInit = 
     new Marker("field Initializer");
   private Marker fieldInit2 =
     new Marker("2nd field Initializer");

   private Marker ctorInit;

   public BaseTrackType()
   {
     ctorInit = new Marker("Ctor Initialized");
   }
}
comments powered by Disqus

Featured

  • VS Code Keeps Eye on Costs in v1.126 Update

    Visual Studio Code 1.126 adds session-level Copilot cost information, continuing Microsoft's recent focus on helping developers monitor and manage usage-based GitHub Copilot billing.

  • Open VSX 1.0.0 Puts Focus on Open Extension Registry for VS Code Ecosystem

    Eclipse Open VSX has reached 1.0.0, highlighting its role as a vendor-neutral registry for VS Code-compatible extensions.

  • Infragistics Puts MCP Toolchain at Center of Ultimate 26.1

    Infragistics Ultimate 26.1 introduces the Ignite UI Enterprise MCP toolchain for AI-assisted app development across Angular, React, Web Components and Blazor.

  • VS Code 1.125 Adds Copilot Spend Meter After Billing Shock

    VS Code 1.125 adds in-editor visibility into additional Copilot budget usage as GitHub's AI-credit billing model continues to draw developer scrutiny.

Subscribe on YouTube