C # syntactic sugar,

Source: Internet
Author: User

C # syntactic sugar,

The first thing to declare is that the word "syntactic sugar" is not a negative term. It can bring convenience to me. It is a convenient way of writing. The compiler will help us with the conversion; in addition, it can improve the development coding efficiency without compromising the performance. This envy java developers.

 

1. Simplified Property

Earlier, we declared the Property

?
1234567891011 private string _myName; public string MyName {     get return _myName; }     set { _myName = value; } }

The same statement does not make much sense, so the C # designer handed the same job to the compiler to help us. Now we can declare it like this.

?
1 public string MyName { getset; }

Of course, he will not sacrifice flexibility. We can set access restrictions for get or set separately, for example

?
1 public string MyName { getprotected internal set; }

 

2. Commissioned writing after two variations

In. net 1.1, We have to declare the method before using it in the delegate. after net 2.0, we can use anonymous delegation. It can not only simplify the writing, but also access the variables in the scope in the anonymous delegation. Later, lambda expressions will simplify the writing.

?
1234567891011121314151617181920212223242526272829 class MyClass{    public delegate void DoSomething(int a);     // Define method Delegation    private void DoIt(int a) {        Console.WriteLine(a);    }     private void HowtoDo(DoSomething doMethod,int a) {        doMethod(a);    }     public static void Main(string[] args) {        MyClass mc = new MyClass();        // Call the defined method delegate        mc.HowtoDo(new DoSomething(mc.DoIt), 10);        int x = 10;        // Use anonymous Delegation        mc.HowtoDo(delegate(int a){            Console.WriteLine(a + x);        },10);         // Use the lamda expression        mc.HowtoDo(a=>Console.WriteLine(a+x),10);         Console.ReadLine();    }}

3. Collection class declaration

Previously, we declared a List and assigned the initial value to the list, which must be written as follows:

?
1234 List<string> list = new List<string>();list.Add("A 1");list.Add("B 2");list.Add("C 3");

You don't need it now. Just write it directly.

?
123 List<string> list = new List<string> {            "def","OK"};

 

4. Operations of various items in the Collection class

To process items in the set one by one, we need to write the following:

?
1234 foreach (string item in list){     Console.WriteLine(item);}

No, so you can.

?
1 list.ForEach(a => Console.WriteLine(a));

Isn't the code refreshing a lot.

 

5. using = try finally

To release resources when they are used up, we often use using, which is essentially a syntax sugar of try fiannaly. For example

?
123456789 StreamWriter sw = null;try{    sw = new StreamWriter("d:\abc.txt");    sw.WriteLine("test");}finally {    if(sw!= null) sw.Dispose();}

The above code can be simplified:

?
123 using (var sw = new StreamWriter("d:\abc.txt")) {    sw.WriteLine("test");}

6. Cute var

The Declaration type does not need to be written in the sense of var. the compiler will judge its type based on the value assigned to var later. Once confirmed, the var type cannot be changed and can only be used as a local variable, it cannot be used as a field or as a parameter declaration.

For example:

?
1 var writer = new StreamWriter(path);
?
1 for(var i=0;i<100;i++){}

 

7. Question Mark Evolution

A question mark + colon

?
12 var b = 3;var a = b > 9?b.ToString():”0”+b;

Two question marks for the new baby ??, It indicates that if the left variable is null, the value is the right variable; otherwise, it is the left variable value.

?
12 string a = null;var b = a??””;

 

8. Type instantiation syntax sugar

?
12345678 public class Abc{    public int ID { getset; }     public string Name { getset; }     public string Url { getset; }}

We didn't declare the constructor for the above class, but we can instantiate it in the following form.

?
1234567 public static void Main(string[] args) {        var abc = new Abc{            ID=1,            Name="yukaizhao",            Url="http://yukaizhao.cnblogs.com/"        };    }

 

9. The legendary Extension Method

The extension method is introduced in c #3.5. It makes sense to add an instance method to the class without modifying the class source code. Its essence is also the implementation of syntactic sugar.

For example, we extend an IsNumber to the String class:

?
1234567891011 public static class StringExt {    static private Regex regexNumber = new Regex("\\d+");    static public bool IsNumber(this string input)    {        if (string.IsNullOrEmpty(input))        {            return false;        }        return regexNumber.IsMatch(input);    }}

We can call this method on the String instance.

?
12 var abc = “123”;var isNumber = abs.IsNumber();

 

10. Use an anonymous class

?
123 var a = new {    ID = 1,Name=”yukaizhao”,BlogUrl=”http://www.cnblogs.com/yukaizhao/”};

The anonymous class is useful when returning data for query in the linq to SQL or entity framework.

If you have more syntactic sugar, please share it with us. At the same time, I hope everyone can enjoy the syntactic sugar, because it can bring us convenience. Please do not sneer at it, and there is no need to sneer at it.

Reprinted from: http://www.timetowhere.com/post/grammar_sugar.html

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.