C # as Operator

Source: Internet
Author: User

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

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.