An Abstract Example
The following demonstrates the abstract method above. The following form code assumes a form with a button.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CR_Abstraction
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Series600 MyKiller = new Series600();
MyKiller.Speak("I'll be back.");
MyKiller.Greet();
}
}
abstract public class Cyborg : System.Object
{
abstract public void Speak(string pMessage);
abstract public void Walk();
public void Greet()
{
MessageBox.Show("Hello");
}
}
public class Series600 : Cyborg
{
public override void Speak(string pMessage)
{
MessageBox.Show(pMessage);
}
public override void Walk()
{
//Implement walk here.
}
}
}
Abstract Properties
C# does support setting a property to abstract with the abstract keyword. A single property line with the abstract keyword along with indicating empty get; and set; methods is all that's required. In most cases, you'll probably also want to define the property's supporting member field as protected for visibility in descendant classes.
For example, we could enhance our classes above as follows:
public abstract class Cyborg : System.Object
{
protected string cyborgName; //Suggested member field
public abstract string CyborgName {get; set;} //Abstract property.
public abstract void Speak(string pMessage);
public abstract void Walk();
public virtual void Greet()
{
MessageBox.Show("Hello human");
}
}
public class Series600 : Cyborg
{
public override string CyborgName
{
get
{
return cyborgName;
}
set
{
cyborgName = value;
}
}
public override void Speak(string pMessage)
{
MessageBox.Show(pMessage);
}
public override void Walk()
{
//Implement walk here.
}
public override void Greet()
{
MessageBox.Show("Hello, I am " + CyborgName + ".");
}
}
Now you can use our newly modified class as follows:
Series600 MyKiller = new Series600();
MyKiller.CyborgName = "John";
MyKiller.Greet();
MyKiller.Speak("I'll be back.");
First Class Requirement
Visual Studio requires that designers use the first class in the file. Notice above that our Cyborg and Series600 classes come after the Form1 class. This is not normally an issue because classes are usually put in their own class file. For demos, I like to put the classes in a simple project with a single form with a single button on it that exercises the exercise.
Summary
Abstraction is an important aspect of your software design and C# implements a robust set of abstract features. To learn more about how abstract classes are similar concepts to interfaces, how they relate to Plato's Forms theory, and more, read our Abstract Members / Class definition article next.