Type safety in .NET has been introduced to prevent the objects of one type from peeking into the memory assigned for the other object. Writing safe code also means to prevent data loss during conversion of one type to another.
What does it exactly means? Suppose I have two types defined as in the following:
- public class MyType
- {
- public int Prop{ get; set;}
- }
- public class YourType
- {
- public int Prop{get;set;}
- public int Prop1{get;set;}
- }
Now suppose, I create an object of MyType as in the following:
- MyType obj = new MyType();
In memory obj would be referencing the 4 bytes of space and suppose next to that part of memory is another string. Now suppose I cast my obj to YourType that thankfully is not at all possible in .NET but for a moment imagine that it would have been possible, in that case my code would look something as in the following,
- YourType obj1 = (YourType)obj;
And suppose, I assign Prop using obj1 reference, as shown below:
Which is fine but suppose I want to assign value to Prop1 as shown below:
That can lead to some unpredictable results and bugs since this part of memory could be used by the string that I have talked about earlier. From this we can say that type safety comes to our rescue, when the compiler would not allow the casting that we have tried to do. This is a relief for the programmers with a background in unmanaged programming.
Now I want to discuss one more scenario in which type safety comes to our rescue. If we are using out or ref with our method parameter and when calling the method our argument does not match the method's parameter, the compiler would not allow the code to compile.
Let's take an example for it. I have user type defined as in the following:
- public class SomeType
- {
- }
And I have function that takes a parameter of type object as shown below:
- private void ChangeValue(out object par)
- {
- par = new String('x', 10);
- }
Now suppose I call the method ChangeValue as in the following that would not of course compile:
- SomeType obj = new SomeType();
- ChangeValue(out obj);
If .NET would have allowed this code to execute, type safety could have easily been compromised here.
If the ChangeValue function has the parameter without the out keyword, there would not have been any compile time error, since the caller can have an argument type that derives from the parameter type.