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'.
public class StaticallyTypedCSharp | |
{ | |
[Fact] | |
public void StaticTypeWontCompile() | |
{ | |
Object o = "Hello"; | |
Assert.True(o.Length == 5); | |
} | |
[Fact] | |
public void StaticTypeCompileEnforced() | |
{ | |
Object o = "Hello"; | |
Assert.True(((string)o).Length == 5); | |
} | |
} |
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.
public class ExplicitTyping | |
{ | |
// This would have failed in C# 1 and 2, prior to the introduction of var in 3.0 | |
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var | |
[Fact] | |
public void ImplicitTypingWillFail() | |
{ | |
var s = "Hello"; | |
var x = s.Length; | |
var twiceX = x * 2; | |
} | |
[Fact] | |
public void ExplicitTypingSucess() | |
{ | |
string s = "Hello"; | |
int x = s.Length; | |
int twiceX = x * 2; | |
} | |
} |
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.
[Fact] | |
public void ThisIsSafe() | |
{ | |
int a = 5; | |
int b = a + 2; //OK | |
bool test = true; | |
// Error. Operator '+' cannot be applied to operands of type 'int' and 'bool'. | |
int c = a + test; | |
} | |
[Fact] | |
public void ThisIsUnSafe() | |
{ | |
var integers = new ArrayList(); | |
integers.Add(1); | |
integers.Add(2); | |
integers.Add("3"); // **PROBLEM** | |
for (int i = 0; i < integers.Count; ++i) | |
{ | |
int integer = (int)integers[i]; | |
// do something | |
} | |
} | |
} |
Reference
Top comments (0)