#952 – Type Safety
October 15, 2013 2 Comments
C# enforces type safety. Type safety is the idea that you can only interact with an object in ways that are allowed by the object’s type. You can’t treat an instance of one type like it is actually an instance of another type.
Below is an example of some C++ code that is not type safe. We use a pointer to treat a floating point value as an integer. This results in an unexpected integer value. This behavior is not normally something that you cannot do in C# (without marking the code as “unsafe”).
double d1 = 1.1; void* ptr = &d1; // Pointer to memory where double is stored int* ptr2 = (int*)ptr; // Use the pointer as a pointer to int int n1 = *ptr2; // Treat double as int