I was wondering what is the better method for Casting objects for C#:
MyClassName test = (MyClassName)object;
MyClassName test = object as MyClassName;
I know already that if you do the first way, you get an exception, and the second way it sets test as null. However, I was wondering why do one over the other? I see the first way a lot, but I like the second way because then I can check for null…
If there isn’t a ‘better way’ of doing it, what are the guidelines for using one way or the other?
Not any official guideline, but here’s how I’d do it.
If you actually want the exception (i.e. you think that the object can never, ever, be of a different type than
MyClassName), use the explicit cast. Example (WinForms):If you want to handle types that are not
MyClassNamegracefully, use theaskeyword.