Syntax sugar in C,

Source: Internet
Author: User

Syntax sugar in C,
1. using replaces try... Catch... Finally

 

Because I used to learn Java before, I naturally used try to connect to the database or perform file read/write operations... Catch... Finally ..., In C #, writing like this is certainly acceptable, but there is also a more elegant way of writing (I see others say this), that is, using the using keyword.

When a variety of streams or connections are used [file read/write streams, database connections, etc.], after use, you need to close the stream and connection (here we do not discuss the need to return the database connection to the pool)

The previous Code is as follows:

Public void Test1 () {SqlConnection conn = null; SqlDataReader reader = null; try {string strConn = ConfigurationManager. connectionStrings ["strConn"]. toString (); conn = new SqlConnection (strConn); conn. open (); SqlCommand cmd = conn. createCommand (); cmd. commandText = "XXXXXXXXX"; reader = cmd. executeReader (); // some operations} catch (Exception e) {Console. writeLine ("error !! ");} Finally {if (conn! = Null) {conn. Close (); conn. Dispose () ;}if (reader! = Null) {reader. Dispose ();}}}

 

The using keyword is used as follows:

Public void Test2 () {string strConn = ConfigurationManager. connectionStrings ["strConn"]. toString (); using (SqlConnection conn = new SqlConnection (strConn) {using (SqlCommand cmd = conn. createCommand () {cmd. commandText = "XXXXXXXXXX"; using (SqlDataReader reader = cmd. executeReader () {// some operations }}}}

For the using Keyword, it is necessary to clarify "managed resources" and "unmanaged resources". Only unmanaged resources need to use the using keyword.

For more information about unmanaged resources and managed resources, see this blog 【]

2. Field omitted

I still remember that when I used a 6-character shortcut key for reading and writing segments in Java, there were no similar objects in C #. Of course there were some shortcut keys, but there were even more powerful ones, the compiler automatically generates fields based on the read/write attributes.

public class Person    {        public string Name { get; set; }        public int Age { get; set; }        public string Sex { get; set; }    }

The compiler automatically generates fields during compilation. The following is the directory of the compiled IL code. Three fields are generated at the bottom.

3. Two question marks "?" Function

A question mark has been seen. It is in the three object element operator. What about two question marks?

This is also a wonderful way of writing. Check the Code:

public class Program    {        public static void Main(string[] args)        {            string a = null;            var b = a ?? "woaini";            Console.WriteLine("b : " + b);            Console.WriteLine("=============");            a = "msym";            var c = a ?? "woaini";            Console.WriteLine("c: " + c);        }    }

Running result:

The conclusion is: If the left side of the question mark is null, It is the value on the right side of the question mark, and vice versa, it is the value on the left side of the question mark.

4. Extension Method

For details, refer to this blog [C # extension method]

This blog also describes the use of extension methods [Application of extension methods]

In fact, my understanding of the extension method is a special tool class, but it is bound with the type. This is just my understanding for the moment, because it does not involve the underlying layer.

 

 

[To be continued]

 

[Back to homepage]

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.