You cannot ignore the usefulness of using and as operators in C # _ Practical Tips

Source: Internet
Author: User
Aren't many people using the use and as operators in C #? Don't even know?
In fact, these 2 operators are very useful in small.

1, using
As explained in MSDN

The using statement defines a scope at the end of which the object is processed.
Example:

Class Testusing:idisposable
{
public void Dispose ()
{
Console.WriteLine ("Dispose");
}

public void Method ()
{
Console.WriteLine ("Do a Method");
}
}
Call this class:


using (testusing tu=new testusing ())
{
Tu. Method ();
}
You can see the output of do a and dispose.
Note: Instantiated objects must implement the System.IDisposable interface

2, as
MSDN says:


The as operator is used to perform conversions between compatible types.
The as operator is similar to a type conversion, but when the conversion fails, the AS operator produces null instead of throwing an exception. In form, the expression of this type:

Expression as type
is equivalent to:

Expression is type? (type) expression: (type) NULL
Only expression are counted once.

Note that the AS operator only performs reference conversions and boxing conversions. The as operator cannot perform other transformations, such as user-defined conversions, which should use cast expressions instead of their execution.


Example:
Object [] arr=new object[2];
arr[0]=123;
arr[1]= "Test";
foreach (Object o in arr)
{
String s= (String) o;
Console.WriteLine (s);
}
Such code throws an exception when the conversion type fails, and the code is modified to:
Object [] arr=new object[2];
arr[0]=123;
arr[1]= "Test";
for (int i=0;i<arr. length;i++)
{
String S=arr[i] As string;
if (S!=null) Console.WriteLine (i+ ":" +s);
You can see the output is 1:test, although Arr[0] failed the conversion but did not throw an exception but returned null

Note: As must be used with reference types (int equivalence type cannot be used)

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.