Thursday, August 25, 2011

What is Type Safe in .Net?

Posted by Rahul Kharde at 3:13 AM

This Article discusses “What is Type Safety?” in the context of .NET,
1) Type-safe code accesses only the memory locations it is authorized to access.
2) For example, type-safe code cannot directly read values from another object's private fields or code areas.
3) It accesses types only in well-defined, allowable ways, thereby preventing overrun security breaches.
4) Type safety helps isolate objects from each other and therefore helps protect them from inadvertent or malicious corruption.
5) It also provides assurance that security restrictions on code can be reliably enforced.
Type-safe code accesses only the memory locations it is authorized to access. ( type safety specifically refers to memory type safety.) For example, type-safe code cannot read values from another object's private fields. It accesses types only in well-defined, allowable ways.
Type safety means that the compiler will validate types while compiling, and throw an error if you try to assign the wrong type to a variable.
Example 1:
// Fails, Trying to put an integer in a string
String one = 1;
// Also fails.
int foo = "bar";
This also applies to method arguments, since you are passing explicit types to them:
int AddNumbers(int a, int b)
return a + b;
If I tried to call that using:
int Sum = AddNumbers(6, "6");
The compiler would throw an error, because I am passing a string ("6"), and it is expecting an integer.
this basically means that you can substitute a base type for a child type and not cause an error,
Example 2
For non-typesafe behavior, consider this:
object x = 89;
int y;
if you attempt to do this:
y = x;
the compiler throws an error that says it can't convert a System.Object to an Integer. You need to do that explicitly. One way would be:
y = Convert.ToInt32( x );
The assignment above is not typesafe. A typesafe assignement is where the types can directly be assigned to each other. 
Example 3
public class Foo : Bar
Here, I created a new class (Foo) that subclasses Bar. I can now create a method:
void DoSomething(Bar myBar)
And call it using either a Foo, or a Bar as an argument, both will work without causing an error. This works because C# knows that any child class of Bar will implement the interface of Bar.
However, you cannot do the inverse:
void DoSomething(Foo myFoo)
In this situation, I cannot pass Bar to this method, because the compiler does not know that Bar implements Foo's interface. This is because a child class can (and usually will) be much different than the parent class.

If you enjoyed this post and wish to be informed whenever a new post is published, then make sure you subscribe to my regular Email Updates. Subscribe Now!

Kindly Bookmark and Share it:



Have any question? Feel Free To Post Below:


Popular Posts

Recent Comments

© 2011. All Rights Reserved | Help to understand .Net | Template by Blogger Widgets

Home | About | Top