I think an overloading of the Indexer and the Add methods is quirky, but
can be justifiable, especially if all coders involved understand the
possible downsides. The plus side is that there may be less code and
increased convenience for the person coding to the class. The downside
is that it is going to be harder for humans to understand, unless they
are familiar with it, and there may be a performance penalty depending
on the kind of indexer used.
here's an example:
public class Unit
{
//this class will hold the bool and double dictionaries of values
private Dictionary<int, doublemydoubles = new Dictionary<int,
double>();
private Dictionary<int, boolmybools = new Dictionary<int, bool>();
#region Indexers
public bool this[int index]
{
get { return mybools[index]; }
set { mybools[index] = value; }
}
public double this[uint index]
{
get { return (mybools[(int)index]) ? 1d : 0d; }
set { mybools[(int)index] = (value == 1d) ? true : false; }
}
public double this[double index]
{
get { return mydoubles[(int)index]; }
set { mydoubles[(int)index] = value; }
}
#endregion
#region Add methods
public void Add(int index)
{
mybools.Add(index, false);
}
public void Add(uint index)
{
mybools.Add((int)index, false);
}
public void Add(double index)
{
mydoubles.Add((int)index, 0);
}
public void Add(int index, bool value)
{
mybools.Add(index, value);
}
public void Add(uint index, double value)
{
mybools.Add((int)index, ((value == 0)?false:true));
}
public void Add(double index, double value)
{
mydoubles.Add((int)index, value);
}
#endregion
public Unit Clone()
{
Unit temp = new PLCUnit();
foreach (KeyValuePair<int, boolkvp in mybools)
temp.Add(kvp.Key, kvp.Value);
foreach (KeyValuePair<int, doublekvp in mydoubles)
temp.Add((double)kvp.Key, kvp.Value);
return temp;
}
}
//The overloading is especially helpful when setting bools from doubles
and vice versa
//especially if this happens a lot
myUnit[1234u] = dblvalue;
//is much easier on the coder than
myUnit[1234] = ((dblvalue == 0)? false : true);
*** Sent via Developersdex http://www.developersdex.com ***