I'm not sure I see the harm in providing a virtual function to be called
from my constructor if it provides for "optional" constructor functionality.

This is a bad example, but let's say we had the following code-- why
wouldn't this be a valid use of a virtual method in a constructor?

public class Fred
{
        public Fred()
        {
                LogMessage("Constructor");
      }

      protected virtual void LogMessage(string strMessage)
      {
                System.Console.WriteLine(strMessage);
        }
}

public class Pebbles : Fred
{
        //Override LogMessage function to write to debug instead of Console
        public override void LogMessage(string strMessage)
        {
                System.Environment.Debug.WriteLine(strMessage);
        }
}


-----Original Message-----
From: Stefan Holdermans [mailto:[EMAIL PROTECTED]
Sent: Thursday, June 19, 2003 3:11 PM
To: [EMAIL PROTECTED]
Subject: Re: [ADVANCED-DOTNET] Partially constructed objects in C#


John,

>You missed his point.

Then, exactly, what is his point?

>So break the init into critical and non-critical, with the
>non-critical being virtal.

That won't do the trick though. Calling the virtual method from the
constructor is not reliable. That's why FxCorp issues a warning. The method
call being critical or non-critical to construction does not matter here.

I think, as a rule, it's best not to call virtual methods from constructors.
Hence, the FxCorp rule. If you disagree, please let me know why... Maybe it
is me missing the point.

Furthermore, if you want initialization to be customizable, you should
introduce some idiom for it. Perhaps a Initialize method this is *not*
called from the constructor. (This leaves it up to the client to call
it---and I can tell why you're not happy with that, but the life of a
programmer is not always a walk in park, you know... Just think of it as the
construction/initialization complement of Dispose. Maybe you should define
an IDispoable-like interface for it: IInitializable or something...)

Cheers,

Stefan

Reply via email to