Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(MyClassName)object vs. object as MyClassName

Tags:

c#

.net

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?

like image 959
Matthew Doyle Avatar asked Jan 22 '23 08:01

Matthew Doyle


2 Answers

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.

like image 161
Thomas Avatar answered Jan 25 '23 23:01

Thomas


Note that as only works for reference types. If you need to unbox a valuetype, then you must the C-style cast.

like image 39
James Curran Avatar answered Jan 26 '23 00:01

James Curran