(MyClassName) object versus object as MyClassName

I was wondering what is the best method for Casting objects for C #:

MyClassName test = (MyClassName)object; MyClassName test = object as MyClassName; 

I already know that if you do the first method, you get an exception, and the second method sets the test to null. However, I was wondering why one over the other? I see the first way a lot, but I like the second way, because then I can check for zero ...

If there is no better way to do this, what are the recommendations for using this or that method?

+4
source share
6 answers

Not an official guide, but here's how I do it.

If you really want an exception (i.e. you think that an object can never be of a different type than MyClassName ), use an explicit conversion. 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.

+8
source

Note that as only works for reference types. If you need to unzip the valuetype type, you must make a C-style.

+1
source

Well, there is a simple reason to use the as keyword (over casting with brackets): This because the as statement does not execute to throw an exception when it fails, but instead fills the null variable. Checking if the value was null checked to see if the code works or not.

Please note that in the real world you will need exception handling around the entire block if the user selects the wrong dll type or access is denied, or ... well, you get a picture. This means that you can freely use the brackets to throw it - but this is, in my opinion, a more elegant method of doing what you want to know if it succeeded or failed.

source: http://www.nullify.net/Article/181.aspx

0
source

Using the as keyword is safer, as you say, and this is what you should use if you are not 100% sure of the type of object you are trying to execute. Conversely, use the (cast) method if you want an exception if a failure is executed. However, if you also use is , then as becomes redundant. For example, the following code is pretty common:

 MyClass mc; if (someObject is MyClass) { mc = (MyClass)someObject; } 
0
source

If you know that the object is MyClassName, then use the first method (live translation). If you are not sure, use the second method and check the null value or check the type with is before casting directly:

 if (obj is MyClassName) { MyClassName test = (MyClassName)obj; } 
0
source

Check out this article on Prefix Casting vs. As-Casting

The author called the casting prefix "Reliable casting" and as "Fast casting".

He has some good examples of when to use them, and the reasons why fast is not always better. Hope this helps!

0
source

Source: https://habr.com/ru/post/1305783/


All Articles