R
R
Rxd2016-11-20 19:20:31
Database
Rxd, 2016-11-20 19:20:31

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

2 answer(s)
R
Roman, 2016-11-21
@Rxd

dynamic?

R
Rou1997, 2016-11-20
@Rou1997

so FieldPair.Name is of type Object

Not Name, but Value wanted to say.
It is impossible, the cast will be somewhere anyway, either in the FieldPair itself, or outside of it. And why is it?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question