Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get data type for DataRow[myColumn] and cast another variable as that type

Tags:

c#-4.0

I have a class that needs to have a variable of an unknown numeric type. I need to get the data type from a specific column at run time, then cast/instantiate the class variable as that type, and then keep a running total of that column as I iterate rows. I thought about representing my class variable as dynamic, but that doesn't sit right with me. I also thought about using a generic method, but again, I feel like there's a better way to do this. A generic property would be great, but, well, you know how that story ends.

Updated, here's what's left of the code I've been working with:

dynamic dc = dataRow["MyColumnName"];
var tempValue = Convert.ChangeType(dataRow["MyColumnName"], Type.GetType(dc.GetType().ToString())); 
total+= (Decimal)tempValue;
like image 755
YuckMouth Avatar asked Dec 03 '25 12:12

YuckMouth


1 Answers

This works for me

if (dtRow.Table.Columns["Date"].DataType == typeof(System.DateTime))
like image 124
Juver Paredes Avatar answered Dec 06 '25 23:12

Juver Paredes