what is  unsafe  and  safe cast  in C# with an example does safe casts avoid exceptions

banu111
banu111 used Ask the Experts™
on
what is  unsafe  and  safe cast  in C# with an example does safe casts avoid exceptions
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
the point of your question isn't apparent to me but if you want to know the type of the object b/f you cast it you can use...

yourObject.GetType();
Commented:
In some reference type conversions, the compiler cannot determine whether a cast will be valid. It is possible for a cast operation that compiles correctly to fail at run time. As shown in the following example, a type cast that fails at run time will cause an InvalidCastException to be thrown.

C#


class Animal
{
    public void Eat() { Console.WriteLine("Eating."); }
    public override string ToString()
    {
        return "I am an animal.";
    }
}
class Reptile : Animal { }
class Mammal : Animal { }

class UnSafeCast
{
    static void Main()
    {            
        Test(new Mammal());

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }

    static void Test(Animal a)
    {
        // Cause InvalidCastException at run time
        // because Mammal is not convertible to Reptile.
        Reptile r = (Reptile)a;
    }

}



above from http://msdn.microsoft.com/en-us/library/ms173105.aspx
also see


http://en.wikipedia.org/wiki/Type_safety


hope this helps
Top Expert 2011

Commented:
I'm not sure what you mean by 'safe cast', but C# provides two ways of casting. One that throws an exception if the object is of the wrong type and another one that simply returns null.

object test = "this is a test";

StringBuilder sb1 = test as StringBuilder; // null is assigned to 'sb1', because 'test' is not of type StringBuilder
StringBuilder sb2 = (StringBuilder) test; // throws InvalidCastException

Open in new window

StephanLead Software Engineer

Commented:
A bit too late to respond, wdosanjos was a bit earlier, but here is another example:


if (obj is MyCustomClass)
{
     MyCustomClass mcc = (MyCustomClass)obj;
}

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial