Reputation: 320
I have a method ExecuteQuery
and it is returning a Datatable
object which is a method of object _dataAccess
, this will compile proper with out using System.Data
string query = "select * from UserNeeds where userNeedID =" + item.ParentId;
var result = _dataAccess.ExecuteQuery(query, CommandType.Select);
foreach (var rows in result.Rows)
{
}
but if i changed var and if give orginal type Datatable
it will show comiple time error as we missed System.Data
.
My question is how compiler can understand that System.Data
is the name space when we keep var
as type.
or why it is forcing when we use orginal datatype
in place of var
, how compiler handing the same ?
Upvotes: 0
Views: 68
Reputation: 36
Namespace is a short notation of any object. If you dont specify then you need to give the full object name.
Var is a one time dynamic data type which stores the object types once it creates dynamically with full object name.
Upvotes: 0
Reputation: 460058
var
is not a type by itself, it's a placeholder for the actual type which will be resolved by the compiler. Since DataRowCollection
(returned by DataRable.Rows
) does not implement IEnumerable<DataRow>
but only the non-generic IEnumerable
interface the foreach
object rows
is of type Object
. So you can't use DataRow
properties and methods in the loop.
You need to cast it everytime or let it be casted by the foreach
:
foreach (DataRow row in result.Rows)
{
}
Now you need to add using System.Data
to the top of your file or use
foreach (System.Data.DataRow row in result.Rows)
{
}
So the reason why it compiles with var
without adding the namespace is that the compiler uses System.Object
for the var
because DataRowCollection
yields objects not DataRows.
Upvotes: 2