|Written by Nikos Vaggalis|
|Thursday, 18 November 2010|
Page 1 of 6
Concluding the exploration of what distinguishes weakly typed languages from strongly typed ones, Nikos Vaggalis looks at examples of strong typing.
In Weakly Typed Languages I presented examples of weak typing in Perl, C# and Visual Basic. Here I continue with examples of strong typing.
This articles concludes my discussion Type Systems Demystified which started by looking at the difference between static and dynamic type systems.
C# Strong typing behavior
Now let's see how strongly typed languages behave.
Compare Example 14 with Examples 5 in the eariler article.
Error 1 Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)
However a = a + b; implicitly converts int to double since there is no data loss when converting an int to a double and so this works.
Error 1 The best overloaded method match for 'ConsoleApplication2.MyClass.my_method(int)' has some invalid arguments
Error 2 Argument '1': cannot convert from 'double' to 'int'
The compiler disallowed the implicit conversion from double to int, not because they are unrelated but because there is potential data loss from the conversion. In this case we could easily bypass the check and make the compiler happy by using an explicit cast:
where we effectively tell the compiler that we know that we might lose data but despite that we want to proceed.
Contrast this behaviour with VB.NET (Example 9 in the previous article) which allowed an implicit conversion between related data types (from a double to an int) but with potential data loss (since a double cannot fit into an int). C#, on the other hand, protects us from the possibility of losing data.
Data loss in C
An implict conversion between family-related data types with data loss becomes clear when we use an example in C.
On the other hand the C# compiler allows us to use an explicit cast because the types are related.
However, if instead of a double we tried to pass in a string as a function/method argument, the compiler would not allow the operation to proceed even with an explicit cast as the types are not compatible.
This means that there is no type converter between those types built into the language; a design decision.
|Last Updated ( Friday, 09 November 2012 )|