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):
private void checkbox_CheckedChanged(object sender, EventArgs e) {
// We've hooked up this event only to CheckBox controls, so:
CheckBox checkbox = (CheckBox)sender;
// ...
}
If you want to handle types that are not MyClassName
gracefully, use the as
keyword.
Note that as
only works for reference types. If you need to unbox a valuetype, then you must the C-style cast.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With