Effective C # Principle 3: Select is or as operator instead of coercion type conversion

Source: Internet
Author: User

C # is a strong data type language. Good programming practice means that when you can avoid coercion from one data type to another, we should try our best to avoid it. At some point, however, runtime type detection is unavoidable. In C #, most of the time you want to use the System.Object type for the arguments that invoke the function, because Framwork has defined the prototype of the function for us. You are likely to try to convert those types down into other types of interfaces or classes. You have two choices: use the as operator, or, using the old C style, cast. (Either way, you must also protect the variable: You can try to convert using is, but then convert or cast with AS.)

At any time, the correct choice is to use the as operator for type conversions. Because it is more secure than blind coercion and more efficient at runtime. When converting with the AS and is operators, not all user-defined types can be completed. They are only successful when the Run-time type matches the target type. They will never construct a new object to satisfy the (transformation) requirements.

Look at an example. You write a code that converts an object instance of any type to an instance of a MyType type. That's how you write code:

object o = Factory.GetObject( );
// Version one:
MyType t = o as MyType;
if ( t != null )
{
 // work with t, it's a MyType.
} else
{
 // report the failure.
}

Or you write this:

object o = Factory.GetObject( );
// Version two:
try {
 MyType t;
 t = ( MyType ) o;
 if ( t != null )
 {
  // work with T, it's a MyType.
 } else
 {
  // Report a null reference failure.
 }
} catch
{
 // report the conversion failure.
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.