Type safety in C#
Type safety in .NET refers to the concept of ensuring that variables, objects, and operations are used in a manner consistent with their defined types at compile-time and runtime. It is a fundamental aspect of the .NET framework and helps prevent type-related errors and ensure the reliability and correctness of the code.
Here's an example that demonstrates type safety in C#:
int number = 42;
string text = "Hello, world!";
// Compile-time type checking
number = text; // Error: Cannot implicitly convert type 'string' to 'int'
// Type inference
var result = number + text; // Error: Operator '+' cannot be applied to operands of type 'int' and 'string'
// Runtime type checking
object obj = "Type checking example";
int objLength = ((string)obj).Length; // Error: InvalidCastException - Cannot cast 'obj' from 'string' to 'int'
In this example, we have an 'int' variable named 'number' and a 'string' variable named text. Let's see how type safety comes into play:
-
Compile-time Type Checking:
When we try to assign the value of 'text' to 'number' ('number = text;'), a compilation error occurs. The C# compiler detects the type mismatch and raises an error since we cannot implicitly convert a 'string' to an 'int'. This compile-time type checking prevents us from accidentally assigning incompatible types and catches the error early in the development process.
-
Type Inference:
Using the 'var' keyword for type inference, we try to concatenate 'number' and 'text' ('var result = number + text;'). However, the compiler raises an error because the + operator is not defined for an 'int' and a 'string'. This type inference example shows that type safety applies even when the types are not explicitly stated.
-
Runtime Type Checking:
In the runtime type checking example, we have an 'object' variable named obj that holds a string value. We attempt to cast 'obj' to an int and access its Length property ('int objLength = ((string)obj).Length;'). However, this operation throws an 'InvalidCastException' because the runtime type of 'obj' is not compatible with the casted type. This runtime type checking demonstrates the importance of verifying types dynamically during program execution.
These examples illustrate how type safety in C# helps catch type-related errors at compile-time and runtime, ensuring that operations are performed with compatible types and preventing unexpected behavior or exceptions.