I've designed a little struct that should help me deal with Excel columns in terms when the letter index is used. The idea is to use the struct implicitly most of the time for iterations over Excel columns etc.
The struct works in the cases i've intended it to. However, on the one hand, I'm not sure if it isn't a little over the top for a struct and i should rather use a class. On the other hand I was a little surprised why the struct did actually work implicitly when combining it with an integer and assigning it to a string value like this
int rowIndex = 1;
ExcelColumn column = 1;
string cellId = column + rowIndex.ToString();
results in the string
being assigned to
A1
So my questions are:
- Why is that the case?
- Is the struct properly designed for its purpose?
Below is the code for the struct:
public struct ExcelColumn
{
#region Constants
private const int MAX_COLUMN_COUNT = 16384;
#endregion
#region Fields
private readonly int _value;
#endregion
#region Constructors
public ExcelColumn(int columnIndex)
{
if (columnIndex < 1)
throw new IndexOutOfRangeException("Index below 1 not allowed.");
if (columnIndex > MAX_COLUMN_COUNT)
throw new OverflowException("Max Column number exceeded");
_value = columnIndex;
}
#endregion
#region Methods
private string GetValue()
{
string value = "";
int val = _value - 1;
do
{
value = Convert.ToChar(65 + val % 26) + value;
val = (val - val % 26) / 26 - 1;
}
while (val >= 0);
return value;
}
public override string ToString()
{
return GetValue();
}
#endregion
#region Operators
public static ExcelColumn operator +(ExcelColumn x, ExcelColumn y)
{
return new ExcelColumn(x._value + y._value);
}
public static ExcelColumn operator +(ExcelColumn x, int y)
{
return new ExcelColumn(x._value + y);
}
public static ExcelColumn operator +(int x, ExcelColumn y)
{
return new ExcelColumn(x + y._value);
}
public static ExcelColumn operator ++(ExcelColumn x)
{
return new ExcelColumn(x._value + 1);
}
public static ExcelColumn operator -(ExcelColumn x, ExcelColumn y)
{
return new ExcelColumn(x._value - y._value);
}
public static ExcelColumn operator -(ExcelColumn x, int y)
{
return new ExcelColumn(x._value - y);
}
public static ExcelColumn operator -(int x, ExcelColumn y)
{
return new ExcelColumn(x - y._value);
}
public static ExcelColumn operator --(ExcelColumn x)
{
return new ExcelColumn(x._value - 1);
}
public static implicit operator ExcelColumn(int x)
{
return new ExcelColumn(x);
}
public static explicit operator int(ExcelColumn x)
{
return x._value;
}
#endregion
#region Properties
public string Value { get { return GetValue(); } }
public int Index { get { return _value; } }
#endregion
}
int
norExcelColumn
define an implicit conversion to string, I'm finding it hard to believe that this compiles:string cellId = column + rowIndex;
. \$\endgroup\$.ToString();
call. Edited it in the question. \$\endgroup\$