Link to home
Start Free TrialLog in
Avatar of banu111
banu111

asked on

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

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

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();
ASKER CERTIFIED SOLUTION
Avatar of Ess Kay
Ess Kay
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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

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