Type Safety in .NET






2.57/5 (11 votes)
Type safety in .NET
Introduction
Type safety in .NET has been introduced to prevent the objects of one type from peeking into the memory assigned for the other object.
What exactly does it mean? 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; // Here we will get compile time error
And suppose I assign Prop
using obj1
reference, as shown below:
obj1.Prop = 10;
Which is fine but suppose I want to assign value to Prop1
as shown below:
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 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 a 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); //compile time error
If .NET would have allowed this code to execute, type safety could have easily been compromised here resulting in some unpredictable results and hence in turn reducing the credibility of the code.
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.