Solved

Casting : If cast fails else

Posted on 2006-06-19
2
189 Views
Last Modified: 2010-04-16
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
Comment
Question by:directxBOB
2 Comments
 
LVL 11

Accepted Solution

by:
Expert1701 earned 500 total points
ID: 16938828
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
 

Author Comment

by:directxBOB
ID: 16939009
Try catch was what I went for in the end. But thanks for the other alternatives very handy to know.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduction                                                 Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.   Also called…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This video discusses moving either the default database or any database to a new volume.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now