Is it possible to have a DataColumn in a DataTable that contains int and long values? It should return an int value if a valid int else it should return a long value.
For some background why I want to achieve this, I have released a product that creates the DataColumn of type int, but it should have been long from the start. Now I don’t want to break existing projects that explicitly casts the value to int, but I would like to allow long values in the column.
Is there an event I can subscribe to on the DataTable to convert the value to int?
The following code should execute correctly.
DataTable dataTable = new DataTable();
dataTable.Columns.Add("IntAndLong", typeof(long));
DataRow intRow = dataTable.NewRow();
intRow[0] = 123;
dataTable.Rows.Add(intRow);
DataRow longRow = dataTable.NewRow();
longRow[0] = 3000000000;
dataTable.Rows.Add(longRow);
long longValue = (long)dataTable.Rows[1][0];
int intValue = (int)dataTable.Rows[0][0];
I would suggest collecting the datacolumn value in a long type variable, check its value to be less than int.MaxValue and bigger than int.MinValue and then cast it to an int variable if you need it there.