Type Safety in .NET

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:
  1. public class MyType  
  2. {  
  3.   public int Prop{ getset;}  
  4. }  
  5. public class YourType  
  6. {  
  7.    public int Prop{get;set;}  
  8.    public int Prop1{get;set;}  
  9. }  
Now suppose, I create an object of MyType as in the following:
  1. 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,
  1. YourType obj1 = (YourType)obj; // Here we will get compile time error  
And suppose, I assign Prop using obj1 reference, as shown below:
  1. obj1.Prop = 10;  
Which is fine but suppose I want to assign value to Prop1 as shown below:
  1. obj1.Prop1 = 20;   
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:
  1. public class SomeType  
  2. {  
  3. }  
And I have function that takes a parameter of type object as shown below:
  1. private void ChangeValue(out object par)  
  2. {  
  3.    par = new String('x', 10);  
  4. }  
Now suppose I call the method ChangeValue as in the following that would not of course compile:
  1. SomeType obj = new SomeType();  
  2. ChangeValue(out obj); //compile time error  
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.


Recommended Free Ebook
Similar Articles