Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of C# var for implicit typing of System.Data.Datarow

foreach (var row in table.Rows)
{
     DoSomethingWith(row);
}

Assuming that I'm working with a standard System.Data.DataTable (which has a collection of System.Data.DataRow objects), the variable 'row' above resolves as an object type, not a System.Data.DataRow.

foreach (DataRow row in table.Rows)
{
     DoSomethingWith(row);
}

Works as I would expect. Is there a particular reason for this?

Thanks.

like image 397
christofr Avatar asked Sep 27 '12 13:09

christofr


People also ask

What is the uses of C language?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...


1 Answers

That's because Rows is DataRowCollection, which in turn is IEnumerable and not IEnumerable<DataRow>, which means that type inferred will be object.

When you explicitly state type in foreach, you instruct c# to add cast to each call, which is why it works.

like image 186
Serg Rogovtsev Avatar answered Sep 21 '22 15:09

Serg Rogovtsev