C# enforces type safety in that it limits you to interacting with an object in ways that are allowed by that object’s type.
C# achieves type safety through the use of both static typing and dynamic typing. (Also referred to as “static type-checking” and “dynamic type-checking”).
Static typing is the process of enforcing type safety at compile-time. The compiler prohibits certain operations, based on the type of the objects involved.
For example:
1 2 | Cat c = new Cat("Fluffy");c.Bark(); |
At compile-time, the compiler flags an error when we try to call the Bark method on our Cat object.
Most type safety is enforced in C# at compile-time (static typing).
Dynamic typing is the process of enforcing type safety at run-time, rather than compile-time. Type-checking can be delayed until run-time by using the dynamic keyword.
1 2 3 | // Compiles ok now, but fails at run-timedynamic c = new Cat("Fluffy");c.Bark(); |

