How about we use a Dictionary
to store any types you need?
So, while you will not exactly have myType.a
, you can have myType.Values["a"]
, which is close enough, makes use of standard C# constructs, and gives you lots of flexibility/maintainability
public class MyType
{
public MyType()
{
this.Values = new Dictionary<object, object>();
}
public Dictionary<object, object> Values
{
get;
set;
}
}
And sample usage:
using System;
using System.Collections.Generic;
public static class Program
{
[STAThread]
private static void Main()
{
var myTypes = new MyType[3];
myTypes[0] = new MyType();
myTypes[1] = new MyType();
myTypes[2] = new MyType();
for (var current = 0; current < myTypes.Length; ++current)
{
// here you customize what goes where
myTypes[current].Values.Add("a", current);
myTypes[current].Values.Add("b", "myBvalue");
myTypes[current].Values.Add("c", (ushort)current);
}
foreach (var current in myTypes)
{
Console.WriteLine(
string.Format("A={0}, B={1}, C={2}",
current.Values["a"],
current.Values["b"],
current.Values["c"]));
}
}
Plus, if you want, you can easily add an indexer
property to your class, so you can access elements with the syntax myType["a"]
. Notice that you should add error checking when adding or retrieving values.
public object this[object index]
{
get
{
return this.Values[index];
}
set
{
this.Values[index] = value;
}
}
And here's a sample using indexer. Increment the entries by '1' so we see a difference in the ouptut:
for (var current = 0; current < myTypes.Length; ++current)
{
myTypes[current]["a"] = current + 1;
myTypes[current]["b"] = "myBvalue2";
myTypes[current]["c"] = (ushort)(current + 1);
}
foreach (var current in myTypes)
{
Console.WriteLine(string.Format("A={0}, B={1}, C={2}",
current["a"],
current["b"],
current["c"]));
}