As far as I know there's no way to add properties dynamically at runtime. Nor is there a way to add properties at compile-time aside from adding them directly to the declaration. In my opinion, this is good as it maintains the type-safety expected from C#.
However, couldn't you make a primitive hashtable using List<KeyValuePair<int, List<KeyValuePair<string, object>>>>
and String.GetHashCode()
? Something like the following (untested and part-pseudocode, but you get the idea):
class HashTable<T>
{
private List<KeyValuePair<int, List<KeyValuePair<string, T>>>> _table =
new List<KeyValuePair<int, List<KeyValuePair<string, T>>>>();
private void Set(string key, T value)
{
var hashcode = key.GetHashCode();
List<KeyValuePair<string, T>> l;
if(!_table.TryGetValue(hashcode, out l))
{
l = new List<KeyValuePair<string, T>>();
_table.Add(hashcode, l);
}
T o;
if(l.TryGetValue(key, out o))
{
if (o != value)
l.Single(x => x.Key == key).Value = o;
}
else
l.Add(new KeyValuePair(key, value));
}
private T Get(string key)
{
List<KeyValuePair<string, T>> l;
object o;
if(!(_table.TryGetValue(hashcode, out l) &&
!l.TryGetValue(key, out o)))
{
throw new ArgumentOutOfRangeException("key");
}
return o;
}
}
The following should help you with TryGetValue
:
public bool TryGetValue<TKey, TValue>(this List<KeyValuePair<TKey, TValue>> list,
TKey key, out TValue value)
{
var query = list.Where(x => x.Key == key);
value = query.SingleOrDefault().Value;
return query.Any();
}