c# Creating objects with a string

My problem was that a particular system had 4 customers and the possibility that this would expand. Each customer had their own bespoke software to handle the data processing. This caused maintenance difficulties as often a change would be required in all 4 programs.

My task was to combine the 4 into a single class, providing a single interface to the order processing software. The tricky bit was how to handle the different business rules of each customer. For example, they had different turnaround and cutoff dates.

To solve this I used abstraction, creating a base class which did all the universal tasks – updating the order book, loading data files in the database etc. Each customer has their own class, inheriting from the base class. The bespoke rules were created as abstract classes, which have to be overridden in the customer class.

abstract class CustomerClass
{
public void PrintName()
{
Console.WriteLine("My name is " + Name());
}
public string Param { get; set; }
abstract protected string Name();
}
class ABCWidgets : CustomerClass
{
public ABCWidgets(string param){}
protected override string Name()
{
return "ABC Widgets";
}
}
class XYZThings : CustomerClass
{
public XYZThings(string param){}
protected override string Name()
{
return "XYZ Things";
}
}

This presented one problem. With a small amount of customers, it is easy to hard code a switch statement to select the right class.

CustomerClass CustomerRules;
switch (Custmer)
{
case "ABCwidget:
CustomerRules = new ABCWidgets();
break;
case 2:
CustomerRules = new XYZThings();
break; 

As more customers come on board, this statement would grow. Changing the core program for each new customer is not really best programming practice. At which point I discovered reflection. This allowed me to have the customers in a configuration file, as I could now create the classes by string.

using System.Reflection;
class Program
{
static void Main(string[] args)
{
string Customer = "ABCWidgets";
Type CustomerType = Assembly.GetExecutingAssembly().GetType(typeof (Program).Namespace + "." + Customer);
CustomerClass Example1 = (CustomerClass)Activator.CreateInstance(CustomerType,"one");
Customer = "XYZThings";
CustomerType = Assembly.GetExecutingAssembly().GetType(typeof(Program).Namespace + "." + Customer);
CustomerClass Example2 = (CustomerClass)Activator.CreateInstance(CustomerType,"two");
Example1.PrintName();
Example2.PrintName();
}
}

The code above is an example of how to create a class. The Customer string would originate from a configuration file or user input. Obviously I still need to create a class for each customer with its bespoke methods, but there will be no changes required to the base class.

previous entry
next entry

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.