[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 198
  • Last Modified:

Casting : If cast fails else

Is there a simple way to test a cast. For example I have a structure that changes from time to time, and if the cast fails move onto an else statement?

Is this possible or wi.l it always throw an exception? Basically what I get is saying that I cant convert my custom type to a bool. But there should be other ways.

Any ideas?
0
directxBOB
Asked:
directxBOB
1 Solution
 
Expert1701Commented:
You can test inheritance using the "is" keyword:

  if(myObject is MyStruct)
  {
    MyStruct myStruct = (MyStruct)myObject;
    //...
  }

But that will not definately check if a cast can be made.  If you were not dealing with a value type you could use the "as" keyword:

  MyClass myClass = myObject as MyClass;
  if (myClass != null)
  {
    //...
  }

Since you are dealing with structs, I think you will have to resort to:

  try
  {
    MyStruct myClass = (MyStruct)myObject;

    //...
  }
  catch(InvalidCastException)
  {
  }
0
 
directxBOBAuthor Commented:
Try catch was what I went for in the end. But thanks for the other alternatives very handy to know.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now