I was working with some legacy code today and noticed something strange. We have some old ADO .NET code that’s reading some data from a database into a DataTable.
At some point in time, the following code
SubscriptionDT.Rows[0]["LastShownBenefits"].ToString().Substring(0, 10)
returned
2001-01-01
However, now it returns
1/1/2001 1
If I quickwatch SubscriptionDT.Rows[0]["LastShownBenefits"] it seems to be able to infer that the type is of System.DateTime. (This column is a DateTime in the database). However, I have a feeling that before we upgraded the project to .NET 3.5, this was probably recognized as a System.Object. Obviously, calling .ToString() returns different results between the two…
My questions are:
1) Am I right about type inference? I thought this might be the case since the var keyword was introduced in .NET 3.5.
2) Is there any documentation available for this change (or similar changes)? I’ve been searching MSDN for some time now, but haven’t been able to find anything.
No, you are not right. The reason is that now a different locale is being used for whatever reason.
That’s why you should always specify the culture in a call to
ToStringto avoid exactly this type of problem.To be clear: This has absolutely nothing to do with type inference. The object was a boxed
DateTimein .NET 2.0 and it still is a boxedDateTimein .NET 3.5.The
varkeyword is strictly a compile time feature. There is no difference in the resulting IL between code using thevarkeyword and code that explicitly specifies the type of a variable, e.g.: