I was wondering what is the better method for Casting objects for C#:
My开发者_开发知识库ClassName 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.
Well, there is a simple reason to use the
as
keyword (over casting using brackets): This is because theas
operator doesn't throw an exception when it fails but instead fills the variable withnull
. The check if the value was null checked if the code worked or not.Note that in the real world you will want exception handling around the whole block, incase the user selects the wrong type of dll, or access to it is denied, or... well, you get the picture. This means you can freely use brackets to cast it - but this is in my opinion a more elegant method of doing something where you want to know if it succeeded or failed.
source: http://www.nullify.net/Article/181.aspx
If you know that the object is MyClassName, then use the first method (direct cast). If you are unsure, then use the second method and check for null or check the type using is
before direct casting:
if (obj is MyClassName)
{
MyClassName test = (MyClassName)obj;
}
Check out this article on Prefix-casting vs As-Casting
The author called prefix casting "Reliable Casting," and as casting "Fast Casting."
He has several good examples of when to use each, and the reasons why fast isn't always better. Hope this helps!
Using the as
keyword is safer as you say, and is the thing to use if you're not 100% sure of the type of the object you're trying to cast. Conversely, use the (cast)
method if you want an exception if the cast fails. However, if you're also using is
, then as
becomes redundant. For example, the following code is quite common:
MyClass mc;
if (someObject is MyClass)
{
mc = (MyClass)someObject;
}
精彩评论