Profile Picture

C# Type System

TypeSystem

Exploring the Terminology:

C# 1's type system is static, explicit, and safe.

Statically typed is where each variable is of a particular type, and that type is known at compile time. In other words, the compiler does type checking at compilation time.

In the test method StaticTypeWontCompile() you can see the string "Hello". But because we gave it the type Object, the compiler sees its type as Object and not String. Hence the .Length method being unavailable. This test won't run because the compiler will state object does not contain a definition for 'Length'.

Explicitly Typed is where the type of every variables must be explicitly stated. Of course, explicit vs implicit types is only relevant in statically typed languages.

Safe Type System is the characteristic of code that allows the developer to be certain that a value or object will exhibit certain properties so that he/she can use it in a specific way without fear of unexpected or undefined behavior.

In the method ThisIsSafe() the compiler will clearly state that an Operator '+' cannot be applied to operands of type 'int' and 'bool'. This safety applies for the majority of C# up until we get to Collections, Inheritance, Overriding and Interfaces as witnessed in method ThisIsUnsafe which compiles perfectly.

Reference

  1. C# In Depth - Jon Skeet
  2. StackOverflow Why Is CSharp Statically Typed
  3. StackOverflow What is Type Safey in .NET
  4. C#s Type System - Microsoft Docs