Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I enforce derived methods to follow a certain pattern?

Tags:

c#

Let's say I have this method in my base class.

public virtual void Close ()
{
    if (!IsOpen) return;

    Dispose();
    RaiseClosed();
}

I want child class to freely modify the method, but make sure it calls Dispose() first, then later it calls RaiseClosed(). They can do anything in before, after, or in between the two.

How can I enforce child classes to call Dispose() and RaiseClosed() at some point?

EDIT: I guess I didn't clarify the question well. Derived methods may do something before/after Dispose(), and before/after RaiseClosed(). So it's not sufficient to make sure it calls Dispose() and RaiseClosed() in an order because the derived methods may do something in between, or even after RaiseClosed().

like image 972
CookieEater Avatar asked Feb 07 '14 07:02

CookieEater


2 Answers

One way is to simply not make Close a virtual method. Instead have another method which is specifically designed to be overriden and call that from your Close method which itself properly enforces the variants you want

public void Close() { 
  if (!IsOpen) return;

  try { 
    CloseCore();
  }
  finally { 
    Dispose();
    RaiseClosed();
  }
}

protected virtual void CloseCore()
{
  // Derived types override this to customize their close
  // behavior 
}
like image 181
JaredPar Avatar answered Nov 07 '22 09:11

JaredPar


First declare the method as not virtual in the following way:

public void Close ()
{
    if (!IsOpen) return;

    DoClosingStuff();

    Dispose();
    RaiseClosed();
}

and then make virtual the method DoClosingStuff()

public virtual void DoClosingStuff()
{
}
like image 25
Trifon Avatar answered Nov 07 '22 09:11

Trifon