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");
}
}