Share via


How to initialize a field before Base Constructor is called

Question

Friday, February 5, 2010 4:04 PM

I have a base class which looks like this:

        protected MyServiceBase()
        {
            SetRequestState();
        }

        private void SetRequestState()
        {
            SetClientState();
        }

        /// <summary>
        /// Sets the state of the client.
        /// </summary>
        protected abstract void SetClientState();

I have a class that inherits the base class that looks like this:

    public class MyService: MyServiceBase
    {
       
        public MyService() : base()
        {
            _client = new SomeSoapBindingObect();
        }

        protected override void SetClientState()
        {
           ...
            _client.SomeProperty = _credentials;
            ...
        }
}

The problem I have is, when the constructor of MyService is called, it calls the base class constructor first.  Then the base class constructor calls eventually the implemented SetClientState() but _client is null because I'm setting it AFTER the base constructor is called.

I don't want to put the _client field in the base Class because the type of _client is dependent on the definition of it in the subclass...I create that there.  So I'm not sure how to get around the timing here and setting of _client.  I need _client of any subclass to be instantiated before the base class constructor is called so that the SetClientState() doesn't bomb out with a Null exception on _client.C# Web Developer

All replies (3)

Friday, February 5, 2010 6:47 PM âś…Answered

Don't call virtual methods in the constructor.

http://msdn.microsoft.com/en-us/library/ms182331.aspx


Friday, February 5, 2010 4:51 PM

Couldn't you define an abstract Initialize method in your base class as so:

        protected MyServiceBase()
        {
            Initialize();
            SetRequestState();
        }

       private abstract void Initialize();

And then define that in your inheriting class:

        private override void Initialize()
        {
            _client = new SomeSoapBindingObect();
        }

Thursday, February 11, 2010 2:05 AM

Hello NoEgo,

As Louis indicated, we highly do not suggest this pattern that calling a virtual function from the base constructor. The bad effect is descriped in the documentation posted by Louis. If you have any other questions or concerns, please let us know.

Regards,
Ji Zhou
MSDN Subscriber Support in Forum
If you have any feedback of our support, please contact [email protected]. Please remember to mark the replies as answers if they help and unmark them if they provide no help.