I recently created a copy of our MySQL DB in SQL Server and the code we were using started crashing because of cast exceptions.
It turned out as a result of the MySQL uint columns being int in SQL Server, however that is a very minor problem and should not crash the program.
The statement Query.GetColumn("AddedColumn") would return a uint under MySQL and int using SQL Server.
MySQL complained about unboxing to uint when I tried casting directly to uint.
To get it working I had to cast to int and then to uint: (uint)(int)Query.GetColumn("AddedColumn").
However, in SQL Server I was getting a cast exception.
I solved all this with the Convert methods: Convert.ToUInt16(Query.GetColumn("AddedColumn")).
I think the Convert methods are bulky and I would much prefer to cast as I was doing.
Also, these methods take about 3 times longer. (See the code below)
Is there an easier way of doing this?
Can the GetColumn method cast for me if I give it the type I want?
Code:
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace CastTest
6 {
7 class Program
8 {
9 static void Main(string[] args)
10 {
11 int Number = new Random().Next(10, 100);
12
13 DateTime Start = DateTime.Now;
14 for (int x = 0; x < 10 * 1000 * 1000; x++)
15 {
16 sbyte SB = (sbyte)Number;
17 byte B = (byte)Number;
18
19 short S = (short)Number;
20 ushort US = (ushort)Number;
21
22 int I = (int)Number;
23 uint UI = (uint)Number;
24
25 long L = (long)Number;
26 ulong UL = (ulong)Number;
27 }
28 DateTime End = DateTime.Now;
29
30 Console.WriteLine("Cast: {0}", End.Subtract(Start).TotalMilliseconds);
31
32 Start = DateTime.Now;
33 for (int x = 0; x < 10 * 1000 * 1000; x++)
34 {
35 sbyte SB = Convert.ToSByte(Number);
36 byte B = Convert.ToByte(Number);
37
38 short S = Convert.ToInt16(Number);
39 ushort US = Convert.ToUInt16(Number);
40
41 int I = Convert.ToInt32(Number);
42 uint UI = Convert.ToUInt32(Number);
43
44 long L = Convert.ToInt64(Number);
45 ulong UL = Convert.ToUInt64(Number);
46 }
47 End = DateTime.Now;
48
49 Console.WriteLine("Convert: {0}", End.Subtract(Start).TotalMilliseconds);
50
51 Console.ReadLine();
52 }
53 }
54 }
55