I am just starting to use abstract classes and would like to know if I am using them in the correct manner. In my example I have a Windows Form application where Form1 is the main UI for the app. Within Form1 I have a method which writes debug messages to a richtextbox. I currently have a bunch of different classes which all have the same method in them to write message back to the main UI richtextbox. However, I was wondering if it would make sense to make this functionality part of an abstract class, an just have all of my other class inherit this functionality as shown below?
using System;
using System.Windows.Forms;
namespace abstractTest
{
/// <summary>
/// Main User Interface
/// </summary>
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void RTBWriteLine(string message)
{
/* Print (append) message to the debug richtextbox */
this.richTextBox1.AppendText(message + Environment.NewLine);
/* Select the last entered message */
this.richTextBox1.Select(richTextBox1.Text.Length, 0);
/* Scroll to selected message */
this.richTextBox1.ScrollToCaret();
}
private void Form1_Load(object sender, EventArgs e)
{
Class1 c1 = new Class1(this);
Class2 c2 = new Class2(this);
}
}
public abstract class absTest
{
protected Form1 MainUI;
public virtual void MainRTBWriteLine(string msg)
{
if (MainUI != null)
{
MainUI.RTBWriteLine(msg);
}
}
}
public class Class1 : absTest
{
public Class1(Form callingForm)
{
MainUI = callingForm as Form1;
MainRTBWriteLine("This is Class1");
}
}
public class Class2 : absTest
{
public Class2(Form callingForm)
{
MainUI = callingForm as Form1;
MainRTBWriteLine("This is Class2");
}
}
}
Edit:
My main goal is that I would to make DTBWriteLine(among many other methods that update the main UI is some way) to be available to all of my classes, but only have the code in one location. Right now, I have the following method (among many others) duplicated in every class I’ve created:
public virtual void MainRTBWriteLine(string msg)
{
if (MainUI != null)
{
MainUI.RTBWriteLine(msg);
}
}
If putting this in an abstract class isn’t the best approach, what is?
Yes, this scenario is a perfect example for using an abstract class.
When you have shared functionality in an inheritance tree.