I’m writing database test utils code which compares DataRow values with expected values supplied as a Dictionary (columnName, expectedColumnValue).
It works fine for many types, but for byte and short I had to add conversion code that converts the values to an Int32.
Two questions:
-
Do you have ideas how to make this code better, i.e. how to avoid the conversion?
For decimal and float it seems to work as they are explicitly declared as a decimal/float value. Long also works without problems. -
If there is no other way, are there any other types apart from short and byte that I need to worry about?
Demo code below:
var table = new DataTable();
table.Columns.Add(new DataColumn("CarrierId", typeof(byte)));
table.Columns.Add(new DataColumn("NotationId", typeof(short)));
var row = table.NewRow();
row[0] = 5;
row[1] = 123;
table.Rows.Add(row);
var expected = new Dictionary<string, object>
{
{"CarrierId", 5},
{"NotationId", 123},
};
foreach (var entry in expected)
{
var value = row[entry.Key];
var expectedValue = entry.Value;
if (value is short || value is byte)
value = Convert.ToInt32(value);
Console.WriteLine();
Console.WriteLine(String.Format("Not converted: {0}", row[entry.Key].Equals(entry.Value)));
Console.WriteLine(String.Format("Converted (if applicable): {0}", value.Equals(expectedValue)));
}
Add the values in their expected type to the dictionary, then you should not need to do the conversion any more when comparing:
When you assign an
intnumber given by a constant expression (known at compile time) to abytevariable, C# automatically converts it tobyte.But when you assign it to an
objectvariable, C# does not know that you will be using it as abytein future and threats it as anintby default.