Avatar of 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 undefined
Last Comment

8/22/2022 - Mon

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...

Ess Kay

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question

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

All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck