Even though the solution is so obvious I should have never have posted this, I’m leaving it up as a reminder and a useful point of reference to others.
I’ve got the following base class:
using System; namespace LibraryWPF { public class Library { /// <summary> /// Event fired when content is added to the libary /// </summary> public event EventHandler<ObjectInfoEventArgs> Library_ObjectAdded; /// <summary> /// Event fired when the scan of the library is finished /// </summary> public event EventHandler Library_Finished; // Properties /// <summary> /// Whether to stop checking the library or not /// </summary> public bool Stop { get; set; } /// <summary> /// Where to look for content /// </summary> public string Root { get; set; } /// <summary> /// Empty instance of library's object for reflection /// </summary> public virtual object ObjectInfo { get { // Should this raise as exception to show if it's not been overridden? return null; } } /// <summary> /// Sub class overrides this method to call it's actual find code /// </summary> public virtual void Find() { // Should this raise as exception to show if it's not been overridden? } /// <summary> /// Build the library /// </summary> public void Build() { if (Root != null && Root.Length > 0) { Stop = false; Find(); } // Final update if (Library_Finished != null) { Library_Finished(this, null); } } /// <summary> /// Sub class calls this method to fire the ObjectAdded event /// </summary> /// <param name='objectInfo'>Object just added to library</param> protected void OnObjectAdded(object objectInfo) { if (Library_ObjectAdded != null) { Library_ObjectAdded(this, new ObjectInfoEventArgs(objectInfo)); } } } }
The sub-classes override ObjectInfo to return an instance of the type of object they’re looking for use by reflection. They also override Find to do the actual searching.
This way my application code can use the base class methods so it doesn’t have to know anything about the sub-classes at compile time. I tell it what sort of content to look for using DI.
So – my question is this:
Should I throw an exception in the base class versions of ObjectInfo and Find so that if the sub-classes aren’t implemented properly I get a run-time error? Or should I code for ObjectInfo returning null?
If you require that a method be implemented by derived classes, why not make it abstract instead of virtual? This will force the derived class to implement the member. If they do not want to, or cannot return an ObjectInfo they can choose to return null themselves.