C # as operator for notes

Source: Internet
Author: User

As Operator

The as operator is used for conversion between compatible reference types.
For example:

String s = someObject as string;
If (s! = Null)
{
// SomeObject is a string.
}

 

 

Remarks
The as operator is similar to the forced conversion operation. However, if the conversion fails, as returns null instead of triggering an exception. See the following expression:

Expression as type

It is equivalent to the following expression, but only evaluates expression once.

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

Note that the as operator only performs reference conversion and packing conversion. The as operator cannot perform other conversions, such as user-defined conversions. Such conversions should be executed using forced conversion expressions.

Example

 

Code 1 // cs_keyword_as.cs
2 // The as operator.
3 using System;
4 class Class1
5 {
6}
7
8 class Class2
9 {
10}
11
12 class MainClass
13 {
14 static void Main ()
15 {
16 object [] bjArray = new object [6];
17 objArray [0] = new Class1 ();
18 objArray [1] = new Class2 ();
19 objArray [2] = "hello ";
20 objArray [3] = 123;
21 objArray [4] = 123.4;
22 objArray [5] = null;
23
24 for (int I = 0; I <objArray. Length;
Related Article

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.