#182 – C# is (Mostly) Strongly Typed

Traditionally, C# has been considered as a strongly typed language.  But with the addition of the dynamic keyword in C# 4.0, you can choose to declare and use dynamically typed variables.  These variables are not type-checked at compile time, but only at run-time.

For example, the following code will not compile.  The String.Concat method is being used incorrectly.  (It’s a static method).

            string s = "Et tu";
            s = s.Concat(" Brutus");   // Compile-time error

In the following example, we declare the variable as dynamic, which means that the type of the variable is only determined at run-time.  No type-checking is done at compile-time.  This code will now compile fine.  The error will only be found at run-time, when an exception is thrown.

            dynamic s = "Et tu";
            s = s.Concat(" Brutus");   // This compiles
Advertisements