Do "type-safe" and "strongly typed" mean the same thing?
What Does Strongly Typed Mean? Strongly typed is a concept used to refer to a programming language that enforces strict restrictions on intermixing of values with differing data types. When such restrictions are violated and error (exception) occurs.
A language is type-safe if the only operations that can be performed on data in the language are those sanctioned by the type of the data. Java is not type-safe, though it was intended to be. A Java object may read and modify fields (and invoke methods) private to another object.
Strongly typed means, a variable will not be automatically converted from one type to another. Weakly typed is the opposite: Perl can use a string like "123" in a numeric context, by automatically converting it into the int 123 . A strongly typed language like python will not do this.
C# is primarily a type-safe language, meaning that types can interact only through protocols they define, thereby ensuring each type's internal consistency. For instance, C# prevents you from interacting with a string type as though it were an integer type.
No, not necessarily - although it depends on your definition of the terms, and there are no very clear and widely accepted definitions.
For instance, dynamic programming languages are often type safe, but not strongly typed. In other words, there's no compile-time type information determining what you can and can't do with a type, but at execution time the runtime makes sure you don't use one type as if it were another.
For example, in C# 4.0, you can do:
dynamic foo = "hello"; dynamic length = foo.Length; // Uses String.Length at execution time foo = new int[] { 10, 20, 30 }; length = foo.Length; // Uses Array.Length at execution time dynamic bar = (FileStream) foo; // Fails!
The last line is the key to it being type-safe: there's no safe conversion from an int array to a FileStream
, so the operation fails - instead of treating the bytes of the array object as if they were a FileStream
.
EDIT: C# is normally both "strongly typed" (as a language) and type safe: the compiler won't let you attempt to make arbitrary calls on an object, and the runtime won't let you perform inappropriate conversions.
I'm not entirely sure where unsafe code fits in - I don't know enough about it to comment, I'm afraid.
Dynamic typing in C# 4 allows weakly typed but still type-safe code, as shown above.
Note that foreach
performs an implicit conversion, making it a sort of hybrid:
ArrayList list = new ArrayList(); list.Add("foo"); foreach (FileStream stream in list) { ... }
This will compile (there was another question on this recently) but will fail at execution time. Ironically, that's because you're trying to be strongly typed with respect to the stream
variable, which means you have to perform a cast on the result of the iterator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With