I am new to generics in C# and while reading a book stumbled upon an example:
var cars = from car in data.AsEnumerable()
where
car.Field<string>("Color") == "Red"
select new
{
ID = car.Field<int>("CarID"),
Make = car.Field<string>("Make")
};
The author says that car.Field<string>("Color") gives the additional compile-time checking comparing to (string)car["Color"]. But how does the compiler know that car.Field<string>("Color") is compilable for “Color” and not for “CarID”? Or there is some kind of another “additional compile-time checking” that I miss?
It doesn’t give you any additional compile-time checking. If you use the wrong type, in both cases you’ll get an exception during run-time.
But it can be useful to do additional stuff that simple cast can’t. For example
Field<int>("CarId")could call a method that converts thestringin the field to anint.And assuming you’re talking about
DataRow.Field<T>(), then, according to the documentation, it’s useful mostly for dealing withnullvalues and nullable types correctly.