"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.
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 Stack myStack = new(); myStack.Push("Hello"); myStack.Push(23); //Queues Queue myQ = new(); myQ.Enqueue("Hello"); myQ.Enqueue(23); //ArrayList ArrayList myAL = new(); myAL.Add("Hello"); myAL.Add(23); myAL.Add(DateTime.Now);
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 myStack.Push(23); ✅ Stack<int> myStack = new(); myStack.Push(80); myStack.Push(23);
Top comments (0)