Mechanic for object initialization after constructor.

Topics: C# Language Design
May 19, 2014 at 8:43 PM
Edited May 22, 2014 at 5:42 PM
I would like to have the C# language introduce an "Initialization" concept that would execute after the constructor has completed, but prior the new reference being returned. As a start, I suggest an attribute could be created to indicate a method to be invoked by the compiler immediately after construction.

I would like to avoid the pattern that I sometimes use now:
var o = new MyObject();
o.Initialize();
Instead, I would like to perform the following:
Class MyObject
{
    public bool MyFlag {get; set;}

    [Initialize]
    protected virtual void Initialize()
    {
        MyFlag = true;
    }

    [STAThread]
    static void Main()
    {
       // Initialize() is called automatically after
       // the constructor has executed.
        var o = new MyObject();
        Assert.IsTrue(o.MyFlag);
    }
}
I find I use this pattern when I create base classes that have standard initialization but are expected to be extended. I would like to contain the initialization and not require/depend on the creator to know the side effects of using the object.
May 19, 2014 at 8:50 PM
The existence of such a feature would have been useful from the start; it needs to be part of the Runtime rather than a language, however. I've suggested something similar: have Object include a virtual method with a parameter of type Exception which would be null if the constructor succeeded, or hold an exception if it failed.

Object constructors which call virtual methods are often fraught with peril, but (in the absence of such a feature) if the base class needs something to happen before control is returned to client code, and that something requires virtual methods, the base class has to use virtual methods before giving control to derived-class constructors, because it won't have any chance to do anything later.
May 21, 2014 at 9:15 PM
I added a possible implementation.
May 22, 2014 at 6:43 AM
msauper wrote:
I would like to have the C# language introduce an "Initialization" concept that would execute after the constructor has completed, but prior the new reference being returned. I have not come up with an acceptable syntax.
The constructor is used for such a purpose. I'm not sure what you mean by "initialization."
Class MyObject
{
    public bool MyFlag {get; set;}

    public MyObject()
    {
        MyFlag = true;
    }

    [STAThread]
    static void Main()
    {
        var o = new MyObject();
        Assert.IsTrue(o.MyFlag);
    }
}
May 22, 2014 at 2:51 PM
Edited May 22, 2014 at 3:04 PM
My example was not intended to justify what I am describing. It was merely to demonstrate the result of what I am describing.

The difference between what I am calling as Initialization and construction is that Initialization method will/can be overridden. Formally, virtual methods should not be called by a constructor because control will potentially be given to a method in an inherited class before the constructor for that class has been executed. This can cause unintuitive problems. As I would like it, the entire object construction will be completed prior to the initialization method being called. I understand that technically, all of the code that I am envisioning could be stuffed into the constructor. However, logically, I find the separation to be easier to understand, extend, and maintain.

I use this design for procedural patterns we use in our business applications. Much of the processing we do follows a similar pattern of selection and looping with only the code in the inner-most loop changing from one object implementation to another. The major structural logic is implemented in base-classes. the inner-most logic is implemented by overriding a stub or abstract method. Sometimes the implementation requires its own custom initialization.

The pattern has worked well for us to develop base classes with virtual methods at specific control points to be overridden to implement the desired behavior. New batch processes can be implemented with little concern to the underlying plumbing. Changes/enhancements to the underlying strategy can be made without affecting the specific implementation.
May 22, 2014 at 3:12 PM
msauper wrote:
The difference between what I am calling as Initialization and construction is that Initialization method will/can be overridden. Formally, virtual methods should not be called by a constructor because control will potentially be given to a method in an inherited class before the constructor for that class has been executed. This can cause unintuitive problems. As I would like it, the entire object construction will be completed prior to the initialization method being called. I understand that technically, all of the code that I am envisioning could be stuffed into the constructor. However, logically, I find the separation to be easier to understand, extend, and maintain.
That means, do you want to do what the class author didn't have in mind when he designed it? Reflection is your friend. :-)
May 22, 2014 at 3:17 PM
The class architect designs the process architecture and specifies extension points. These extension points are implemented by overriding predefined virtual/abstract methods (virtual for optional extension, abstract for required extension). So the class architect develops the business pattern, the business programmer provides the implementation specific details.
May 22, 2014 at 7:17 PM
junyoung wrote:
That means, do you want to do what the class author didn't have in mind when he designed it? Reflection is your friend. :-)
Some objects need to attach themselves to other objects in order to perform their intended function. Ideally, a base class object would refrain from such attachment until after all derived-class constructors had a chance to run, but at present the only way for such attachment to take place is either have it be done within the base-class constructor, or to require that the most-derived class (and only the most-derived class) call an initialization method on the object under construction. Unfortunately, there's no nice way to specify for class Foo to specify that a particular constructor is supposed to be used only to construct instances of Foo without also allowing it to be used to construct instances of derived types.

Incidentally, one thing that I would like to see in a language if a framework could support it (I think this is a framework limitation, rather than just a language limitation), would be the ability to have a method be both overridden and shadowed in the same class, so that the base class would be the main entry point for a function, and derived-class overrides would be wrapped from within those of the base class, rather than the other way 'round. Additionally, it would be helpful if methods' exposures to derived types could be better controlled so that e.g. a concrete type could make a method only available to immediately-derived classes and not sub-derived one (such a declaration would have been appropriate for things like MemberwiseClone), or could specify that an implementation of a virtual method should only be usable by the concrete type, and that from the standpoint of derived types it should be considered "abstract".