Usage of AS and IS Keywords in C

  • 2021-09-12 01:53:17
  • OfStack

Typing is common in programs, and C # supports basic cast methods, such as:


Object obj1 = new NewType();
NewType newValue = (NewType)obj1;

When casting in this way, this process is not safe, so it needs to be protected by try-catch statement. In this way, the safer code mode should be as follows:


Object obj1 = new NewType (); 
NewType newValue = null ; 
try
{
newValue =  ( NewType ) obj1 ; 
}
catch  ( Exception err ) 
{
MessageBox.Show ( err.Message ) ;
}

However, the above writing method is outdated and inefficient in C #. The more efficient and fashionable writing method is to use as operator, as follows:


Object obj1 = new NewType (); 
NewTYpe newValue = obj1 as NewType

Security:

The as operator will not do the conversion operation, when the type of the object to be converted belongs to the conversion target type or a derived type of the conversion target type, then the conversion operation will succeed, and no new object will be generated "if it is unsuccessful, null will be returned". Therefore, it is safe to use as for type conversion.

Efficiency:

When the as operator is used for type conversion, the type of the current object is judged first, and the conversion is carried out only after the type meets the requirements. However, the traditional type conversion method uses the current object to convert directly, and in order to protect the successful conversion, try-catch should be added, so relatively speaking, as has a high efficiency.
It should be noted that after the type conversion is performed by both the traditional and as operators, it is necessary to determine whether the conversion was successful before using it, as follows:


if ( newValue  ! = null ) 
{
//Work with the object named  " newValue " 
}

However, the following points should be noted when using the as operator:

1. There is no need to convert types, that is, compile errors will occur if you write as follows.


NewType newValue = new NewType (); 
NewTYpe1 newValue = newValue as NewTYpe1 ; 

2. Can't be applied to value type data, that is, it can't be written as follows (compile errors will also occur)


Object obj1 = 11 ; 
int nValue = obj1 as int;

For 1., it can be done by traditional type conversion:


NewTypeOne newTestOne = new NewTypeOne (); 
NewTypeTwo newTestTwo =  ( NewTypeTwo ) newTestOne ; 

To complete the above operation correctly, add the type conversion operator function to the original type, that is, you need to complete code similar to the following:


public calss NewTypeOne
{
public static explicit operator NewTypeTwo( NewTypeOne obj1)
{
//Convert object into new type
}
}

For 2, the is operator can be used in C #, and the old-fashioned type conversion operation can safely complete the conversion. To complete the above operation, the correct writing is as follows:


Object obj1 = 11 ; 
if ( objTest is int  ) 
{
int nValue =  ( int ) obj1 ; 
}

The good type conversion methods provided in C # are summarized as follows:

Object = > Known reference type-done using as operator;

Object = > Known value type-first use is operator to judge, and then use type strong conversion mode to convert;

Conversion between known reference types-first, the corresponding types need to provide conversion functions, and then use strong conversion methods for conversion;

Conversion between known value types-preferably using the static methods involved in the system-supplied Conver class.

Let's introduce the use of as keyword in C #

In actual coding, we sometimes use as keyword to convert objects to specified types. Different from is type, is keyword is used to check whether objects are compatible with given types. If compatible, true will be returned, and if incompatible, false will be returned. The as keyword will be directly converted. If the conversion is successful, it will return the converted object. If the conversion is unsuccessful, it will not throw an exception but return null.

Let's create a simple use case to illustrate the use of as:

1. Using visual studio2015 as the development environment, create a new window Form form application and name it TransForm.

2. Add 1 button control to the form for type conversion, 1 GroupBox control, and 3 RadioButton controls to this control for selecting which type.

3. The detailed code is as follows:


private void btn_Get_Checked(object sender,EventArgs e)
{
if(rbtn_object.checked)
{
using (FileStream P_filestream=new FileStream(@'d:\log.txt',System.IO.FileMode.Create))
{
object p_Object = P_filestream as object;
if(p_Object!=null)
{
Message.Box(" Conversion Obejct Success " , " Prompt ") ; 
}
else
{
Message.Box(" Conversion Obejct Failure "," Hint! ")
}
}
if(rbtn_stream.checked)
{
using (FileStream P_filestream=new FileStream(@'d:\log.txt',System.IO.FileMode.Create))
{
obejct p_object=P_filestream;
Stream P_Stream = p_objec as Stream;
if(P_Stream!=null)
{
Message.Box(" Conversion Stream Success " , " Prompt ") ; 
}
else
{
Message.Box(" Conversion Stream Failure "," Hint! ")
}
}
}
}

Related articles: