Answer the question
In order to leave comments, you need to log in
Is automatic type casting possible in c#?
There is a function that makes a query to the database, as a result of which it returns an object of the DataTable class, which contains the result of the query in a convenient format (a list of rows, each of which contains a list of columns). Each cell is of type FieldPair, which contains the name of the column and its actual value. The most interesting thing is that we initially cannot know the type of the database column, so FieldPair.Value is of type Object so that we can store both string and int values in it. However, I noticed that in the debugger the type of this variable looks like " object (int/string)
", in connection with which the question arises: is it possible to somehow use the variable Name immediately as a string or let's say int without constant type casting (like (int)DataTable.Rows[i].Field[j]
) ?
public class FieldPair
{
public string Name;
public object value;
public FieldPair(string _name, object _value)
{
Name = _name;
value = _value;
}
}
private static DataTable Query(OleDbConnection dbConnect, OleDbCommand dbCommand, string sqlQuery, params Object[] values)
{
DataTable qResult = new DataTable();
dbConnect.Open();
dbCommand.CommandText = sqlQuery;
genParamCollection(dbCommand, sqlQuery, values);
OleDbDataReader reader = dbCommand.ExecuteReader();
while (reader.Read())
{
Row tmpRow = new Row();
for (int i = 0; i < reader.FieldCount; i++)
{
tmpRow.Fields.Add(new FieldPair(reader.GetName(i), reader[i]));
}
qResult.Rows.Add(tmpRow);
}
reader.Close();
dbCommand.Parameters.Clear();
dbConnect.Close();
return qResult;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question