One, C # as operator
The as operator is used to perform an explicit type conversion of a reference type. Please read the C # data type.
The as operator can be represented in the following format:
expression as type?expression: expressions of reference types.
? Type: Reference type.
For example:
String str = Someobject As String;
if (str! = NULL)
{
Someobject is a string.
}
The as operator is similar to the cast operation. Just when the conversion fails, the AS operator returns null without throwing an exception.
Second, prompt
Expression as type is equivalent to
Expression is type? (type) expression: (type) null but expression can only be computed once.
Note: If the type being converted is compatible with the specified type, it will be converted successfully, and if the type being converted is incompatible with the specified type, the AS operator will return a null value.
Iii. examples
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Namespace Test
{
Class Program
{
static void Main (string[] args)
{
C # as Operator-www.baike369.com
Object obj1 = "This is a string";
Object obj2 = 9;
String str1 = Obj1 As String; Conversion success
Console.WriteLine ("STR1:" + str1);
String str2 = Obj2 As String; Conversion failed
Console.WriteLine ("STR2:" + str2);
Console.ReadLine ();
}
}
}
Operation Result:
Str1:this is a string
STR2:
STR2 returns NULL.
C # as Operator