Monday, July 13, 2009

Type Safe in C#

When casting from one type to another.C# compiler will check whether the casting wont cause any problem .Then only the casting will happen other wise it throw error "InvalidCastExpression" . This is why .Net is type safe.

We can freely cast form a derived class to a base class .But we cannot blindly convert a base class to a derived class.

E.g1 :
object obj = new object();
string s = (string)obj;
//Error "Unable to cast object of type 'System.Object' to type 'System.String' "

Note : Because system.String is derived from system.Object(base class of .NET ).i.e we are converting from a base class to derived class.

Object obj = "foo";
string str = (string)obj;
//No error

Note : we are converting derived class to a base class.

E.g2:
class classA
{

}

class classB:classA
{
}

class main
{
public static void Main()
{
classA a = new classA();
classB b = (classB)a;
//Error " Unable to cast object of type 'Console_Anisj.classA' to type 'Console_Anisj.classB' "

}
}

Note : Because classB is derived from ClassA.i.e we are converting from a base class to derived class.

class classA
{

}

class classB:classA
{
}

class main
{
public static void Main()
{
classB b = new classB();
classA a = (classA)b;
}
}

Note : we are converting derived class to a base class.

Why this is compailing ?
During compile time compiler checks whether the classA and classB is derived from System.Object class.So it wont throw any error.During run time it will check the base class and derived class.This is the reason the error is throwing in the runtime.

Best way to check the casting by using is and as operator in C#

object obj = new object();
System.Boolean b1 = (obj is System.Object);
System.Boolean b2 = (obj is System.String);

Note : here b1 is true and b2 is false.


classA a = new classA();
classB b = new classB();
System.Boolean b1 = (a is classB);
System.Boolean b2 = (b is classA);

if(b2)
{
classB b = new classB();
classA a = (classA)b;
}

Note : here the b1 is false and b2 is true .CLR wants to check the type twice one out side the
if loop and one inside the if loop. so introduced the new concept as "as"operator.

classA a = new classA();
classB b = new classB();
classA a1 = b as classA;
classB b1 = a as classB;
if (a1 != null)
{
classA a2 = (classA)b;
}
if (b1 != null)
{
classB b2 = (classB)a;
}

Note :if the type can be casting then it returns not null pointer and if it returns null it cannot be cast.CLR wants to check the type only once.so it improve the performance.





0 comments:

 
Counter