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.