3 ms·
Inferring types is cool, if it doesn't create bugs. But it does. Its not a lot of work to just say it outright, and it can save your life.
by JoeAltmaier 13y ago
Inferring types is cool, if it doesn't create bugs. But it does. Its not a lot of work to just say it outright, and it can save your life.
- nlawalker 13y agoCan you elaborate? I'm not sure what you mean.
- JoeAltmaier 13y agoUnexpected conversions can add bugs. Putting a string into a table that was implicitely integer - if your string doesn't start with digits it gets converted to zero. Was that what you intended? Did you think the table would hold a string?
- profquail 13y agoSo it's not actually the type inference that's the problem -- it's developers who carelessly define implicit conversion operators on their classes.
- JoeAltmaier 13y agoStrings have built-in conversion, right?
- nanofortnight 13y agoThe only built-in implicit conversions in C# are for numerics, and there isn't a loss in precision for those (with the exception of int/uint/long/ulong -> float and long/ulong -> double, where there is a loss of precision). http://msdn.microsoft.com/en-us/library/y5b434w4.aspx http://msdn.microsoft.com/en-us/library/y5b434w4.aspx int i = "5"; would not work.
- recursive 13y agoNot the kind you seem to be thinking of.
- nanofortnight 13y agoImplicit conversions != Type inference
- dnissley 13y agoType inference in C# with the var keyword doesn't work like a dynamic language like javascript. It works by simply using var as a placeholder for whatever type the right hand side returns, which is determined at compile time.
- JoeAltmaier 13y agoSo the type depends upon the initial values, which might not be representative of your full intent? A list of strings doesn't guarantee you won't want later to put something else in there. I guess you'd just have to declare it explicitly in that case.
- dnissley 13y agoYep, like if you wanted to put a list behind an IEnumerable interface or something like that, instead of an actual list. It's just a very useful shortcut for the thing you want to do 90% of the time.
- jpatte 13y agoWhy would you want to put anything other than a string in a list of strings ? That's just looking for trouble IMHO.
- laumars 13y agoBut you could explicitly declare the string table and still try to put an integer into it. Your example isn't an issue of type inference, it's an issue with the developer not properly tracking what variables store what types in his/her own code.
- deleted 13y ago[deleted]
- rjbwork 13y agoLiterally never seen a bug from using var. Please elaborate on a common bug you encounter when using var and type inference.