Hi,
I would like to use dictionaries to implement my property value storing mechanics.
(I have a lot but many of them are just about to keep <nullmost of the time, so it might save a lot of memory.)
So, my solution is:
class Person
{
private readonly ReferenceStock<string_strings = new ReferenceStock<string>();
private readonly ValueStock<int_ints = new ValueStock<int>();
private readonly ValueStock<bool_bools = new ValueStock<bool>();
public string Name
{
get { return _strings["Name"]; }
set { _strings["Name"] = value; }
}
public int? Age
{
get { return _ints["Age"]; }
set { _ints["Age"] = value; }
}
public int Rating
{
get { return _ints["Rating", 0]; }
set { _ints["Rating", 0] = value; }
}
public bool? Married
{
get { return _bools["Married"]; }
set { _bools["Married"] = value; }
}
}
where ReferenceStock/ValueStock are:
public class ValueStock<Twhere T : struct
{
private readonly Dictionary<string, T_values;
public ValueStock()
{
_values = new Dictionary<string, T>();
}
public T? this[string name]
{
get
{
if (_values.ContainsKey(name))
return _values[name];
return null;
}
set
{
if (value.HasValue)
_values[name] = value.Value;
else
if (_values.ContainsKey(name))
_values.Remove(name);
}
}
public T this[string name, T defaultValue]
{
get
{
return this[name] ?? defaultValue;
}
set
{
if (value.Equals(defaultValue))
this[name] = null;
else
this[name] = value;
}
}
}
public class ReferenceStock<Twhere T : class
{
private readonly Dictionary<string, T_values;
public ReferenceStock()
{
_values = new Dictionary<string, T>();
}
public T this[string name]
{
get
{
if (_values.ContainsKey(name))
return _values[name];
return null;
}
set
{
if (value != null)
_values[name] = value;
else
if (_values.ContainsKey(name))
_values.Remove(name);
}
}
}
The question is:
Do I have any chances to use the same name instead of ReferenceStock and ValueStock (like C++ templates allow to do in this situation)?
I just want to be able to write the following for every possible type of parameter:
private readonly FieldStock<string_strings;
private readonly FieldStock<int_ints;
private readonly FieldStock<bool_bools;
Thanks,
-- dmitry