As and is operators and secure type forced conversion

Source: Internet
Author: User

I. Introduction

Type security is one of the key considerations at the beginning of. net design.ProgramDesigners are often unable to fully grasp the type security of system data. Now, all this has been solved for you in the design framework of Microsoft's experts. You can use the following methods to obtain the object type information at runtime:

1.1 typeof operator. For example, system. Type type = typeof (Int ?);

1.2 use the classes and methods of the system. Reflection namespace.

1.3 GetType () method. In. net, all types must inherit from the system. Object type, and the system. object class has a GetType () method. However, this method cannot be applied to the null type (the null type can represent all values of the basic type, or the null value ). If you try to use the GetType method or the is operator to obtain the type information of the null type variable at run time, the result is that the basic type of the null type can be obtained, rather than the type object of the null type.

The 1.4as and is operators. According to the description of msdn: because the object is polymorphism, the variables of the base class type can save the derived type. To access a method of the derived type, you must forcibly convert the value back to the derived type. However, in these cases, a simple forced conversion will lead to the risk of invalidcastexception. Because this process is not safe, try-Catch Block must be used for protection. For example, it is saferCodeThe method should be as follows:

 

// There is an object type to be converted object objtest

Giventype value = NULL;

Try

{

Value = (giventype) objtest;

}

Catch (exception E)

{

MessageBox. Show (E. Message );

}

 

However, the above method is outdated in C # and inefficient. However, similar conversions often occur. To avoid inefficiency caused by exceptions and code conciseness, C # provides the is and as operators for conversion. You can use these two operators to test whether the forced conversion is successful without the risk of exceptions.

Ii. Is Operator

The is operator checks whether the object is compatible with the given type. For example, if (obj is myobject) checks whether the object obj is an instance of the myobject type or an instance of the type derived from myobject.

The result of the is expression should be treated as follows: if the provided object (expression) is not empty and can be forcibly converted to the provided type without exception, the result of the is expression is true. Otherwise, the result is false.

Generally, if the is expression is used, the type compatibility is calculated only when the program runs. If the value of the known expression is always true or Fale, a warning will be generated during compilation.

Note: The is operator only considers reference conversion, packing conversion, and unpacking conversion, and does not consider other conversions (including user-defined conversions ). For example, although the int and double types are compatible, the result of using the is operator is false.

 

Other notes:

The is operator cannot be overloaded;

Anonymous methods (except lambda expressions) are not allowed on the left side of the is operator ).

 

Iii. As Operators

 

The as operator is used to perform operations similar to forced type conversion between compatible reference types. Unlike forced type conversion, if the conversion fails, the as operator returns NULL instead of causing an exception.

Syntax:

Expression as type

It is equivalent:

Expression is type? (Type) expression: (type) null

 

Note: The as operator can only perform reference conversion and packing conversion, and cannot perform unboxing conversion (the is operator should be used to determine whether to complete the conversion with forced type loading), and cannot perform other conversions, for example, user-defined conversions (such conversions must first provide the conversion function for the corresponding type and use the forced conversion expression to complete, or use other methods such as case statements to execute ). The following is an example:

 

2.1 you cannot use the as operator to perform box-breaking conversion.

That is, the as operator cannot be used in value-type data. The compilation error may occur when writing the following code:

 

Object objtest = 11;

Int intvalue = objtest as int;

 

The correct method is to use the is Operator and add an explicit type conversion operation to complete the conversion safely. For example:

 

Object objtest = 11;

If (objtest is int)

{

Int intvalue = (INT) objtest;

}

 

2.2 User-Defined conversions cannot be completed using the as operator.

To correctly complete a user-defined conversion operation, you must add the type conversion operator function to the original type. For example:

 

Public class newtypeone

{

Public static explicit operator newtypetwo (newtypeone objtypeone)

{

// Convert object into New Type

}

}

 

And use the following forced type conversion (The as operator is not supported ):

 

Newtypeone objtypeone = new newtypeone ();

Newtypetwo newtesttwo = (newtypetwo) newtestone;

 

2.3 use the null type for the as operator

You can use the as operator to convert between basic data types (known value types). However, since the as operator may generate null values, note that you may need to use the nullable type for the as operator, otherwise, an exception may be thrown.

The following is the code from msdn:

Void useaswithnullable (system. valuetype Val)

{

Int? J = Val as Int ?;

If (J! = NULL)

{

Console. writeline (j );

}

Else

{

Console. writeline ("cocould not convert" + val. tostring ());

}

}

 

Iv. Comparison of the AS and is Operators

 

Generally, the as operator is more efficient, because if forced conversion can be successful, it will actually return the forced conversion value. The is Operator returns only one Boolean value. If the expression is true, you need to convert the display to perform two type compatibility checks. For example:

 

Object o = "ABC ";

If (O is string) // perform the first type compatibility check

{

String S = (string) O; // perform the second type compatibility check and convert

MessageBox. Show ("conversion successful! ");

}

Else

{

MessageBox. Show ("Conversion failed! ");

}

 

The as operator can be rewritten:

 

Object o = "ABC ";

String S = oasstring; // executes the first type compatibility check and returns the result.

If (s! = NULL)

MessageBox. Show ("conversion successful! ");

Else

MessageBox. Show ("Conversion failed! ");

 

In comparison, is requires two object type checks, while as requires an object type check and a null check, however, the null check overhead is less than the object type check. Therefore, the as method is more efficient. Of course, you only need to check whether the types are consistent. If you want to convert the types, you can directly use.

 

V. Summary of type conversion

 

To sum up, you can select the type conversion method as follows.

 

 

Type conversion

Operation

Object --> known reference type

Use the as operator to complete

Object --> basic data type (unpacking)

Use the is Operator for determination, and then use the forced conversion method for conversion.

Conversion between user-defined types

First, you need to provide the conversion function for the corresponding type, and then use the forced conversion method for conversion.

Conversion Between Basic Data Types

It is best to use the static method involved in the convert class provided by. net.

 

Other types of conversions:

 

1. Any type can be converted to its base class type, which can be completed by implicit conversion;

2. Display conversion is required when any type is converted to its derived type. For example: (type name) Object Name;

3. Use GetType to obtain the exact type of any object;

4. The basic data types are all known value types. You can use the convert class to implement type conversion;

5. All types except string have the parse method, which is used to convert the string type to the corresponding basic type;

6. The conversion between the value type and the reference type is called boxing or unboxing ). (According to the msdn programming guide: boxing is the process of converting the value type to the object type or any interface type implemented by this value type. When the CLR loads the value type, the value is encapsulated into system. object, and then stored on the managed stack. Unboxing extracts the value type from the object .)

I talked about some of the common concerns of type conversion. I should focus on the resentment of the IS and as operators. Type conversion will be a big topic and should be discussed at the appropriate time.

The is/as operator is used for type conversion in C #. It provides a judgment on type compatibility, so that type conversion is controlled in a safe category and flexible type conversion control is provided.

 

Is rules are as follows:

Check the compatibility of object types and return results, true or false;

If the object is null, the return value is always false.

 

Refer:

1. How to: securely enforce conversions using the AS and is operators (C # programming guide). msdn. http://msdn.microsoft.com/zh-cn/library/cc488006

2. As (C # reference). msdn. http://msdn.microsoft.com/zh-cn/library/cscsdfbt

3. Is (C # reference). msdn. http://msdn.microsoft.com/zh-cn/library/scekt9xw

4. Usage of As and is in C #. http://www.cppblog.com/luyulaile/archive/2011/03/14/141773.html

5. C # As and is. http://blog.csdn.net/pengfeixiong/article/details/7409875

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.