#953 – Static Typing vs. Dynamic Typing

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:

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.

953-001

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.

// Compiles ok now, but fails at run-time
dynamic c = new Cat("Fluffy");
c.Bark();

953-002

Advertisements