DEV Community

Isaac Ayodeji Ikusika
Isaac Ayodeji Ikusika

Posted on • Updated on


Type safety and strong typing—what are these terms?

"C# is a strongly typed and type safe language". This is one of the first sentences you see as a C# newbie. I did not really care about the meaning of these words when I started out and I think it mostly is because I only saw them as a features of C# and nothing to worry about.

I understood that you cannot implicitly assign some types to each other and that was just it. I also believed that type safety and strong typing have the same meaning.

But I was wrong.

The type safety feature of a programming language simply means the language only allows you to perform the operations allowed by a data type.
Take for example, you cannot perform a IsNullOrEmpty() check on an integer value in C# because it is only allowed on string types.

This permission can happen during runtime and/or compile time, and that is when strong (or static) typing comes in. Strong typing means the permission check will happen at compile time while weak typing means the check will happen at runtime by throwing an exception.

In our example above, the compiler will tell us cannot convert from int to string, making C# strongly typed and type safe.

JavaScript conversely is weakly (or dynamically) typed but type safe. An example of this is how it provides you with a well-defined way to convert a string to an integer, but only gives you an error at runtime when you are parsing the wrong string.

It is advised to use generic collections in C# because the non-generic ones are not type safe. Check the examples below:

using System.Collections

Stack myStack = new();

Queue myQ = new();

ArrayList myAL = new();

Enter fullscreen mode Exit fullscreen mode

Notice that these types allow addition of any data type in them, unlike generic ones, for example:

using System.Collections.Generic

Stack<int> myStack = new();
myStack.Push("Hello"); // => compile time error because the only int type is allowed

Stack<int> myStack = new();

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.