There is actually a clean way to solve this problem; you can use a dictionary with data type keys and values ββthat are of type generic Func <>. You then pass the type to your create method, which then searches for Func <> to use in the dictionary based on that type and calls Func <> to create or process your object.
Since I work from pseudo-code, basically it will look something like this: you can play with it and modify it so that it can satisfy your needs, but this is the main idea.
First create a parent class for all data objects; note that this class has a search dictionary for functions called on different types, and note that it is abstract:
public abstract class Data { // A Lookup dictionary for processing methods // Note this the functions just return something of type object; specialize as needed private static readonly IDictionary<Type, Func<object, Data>> _processFunctions = new Dictionary <Type, Func<object, Data>>() { {typeof(int), d => { return doSomethingForInt( (Data<int>) d); }}, {typeof(string), d => { return doSomethingForString( (Data<string>) d); }}, {typeof(double), d => { return doSomethingForDouble( (Data<double>) d); }}, }; // A field indicating the subtype; this will be used for lo private readonly Type TypeOfThis; protected Data(Type genericType) { TypeOfThis = genericType; } public Data Process() { return _processFunctions[this.TypeOfThis](this); } }
Now a subclass of Data with a typical type that can be created:
class Data<T> : Data { // Set the type on the parent class public Data() : base(typeof(T)) { } // You can convert this to a collection, etc. as needed public T Items { get; set; } public static Data<T> CreateData<T>() { return new Data<T>(); } }
You can then create the DataCollection class using the parent type. Pay attention to the ProcessData () method; all he does now is loop over the elements and call Process () for each of them:
class DataCollection { public IList<Data> List = new List<Data>(); public void ProcessData() { foreach (var d in List) { d.Process(); } } }
... and you're done! Now you can call your DataCollection with various data types:
DataCollection dc = new DataCollection(); dc.List.Add(new Data<int>()); dc.List.Add(new Data<string>()); dc.List.Add(new Data<double>()); dc.ProcessData();