C # syntax sugar (Csharp syntactic sugar) Grand Summary

Source: Internet
Author: User

The first thing to declare is that the word "grammar sugar" is not a derogatory word, it can bring me convenience, is a convenient way to write, the compiler will help us do the conversion, but also to improve the efficiency of the development of coding, the performance will not be a loss. This makes Java developers envy unceasingly, hehe.

1. The Simplified property

Earlier, we declared this property

1234567891011 private  string  _myname;  public  string  myname  {        get  { return  _myname;}       set   {_myname = value;}  

The same kind of statement, not much significance, so the C # designers to the work of this one-size-fits-all compiler to help us do, we can now declare

1 publicstringMyName { get; set; }

Of course he doesn't sacrifice flexibility, we can set access restrictions for get or set alone, for example

1 publicstring MyName { get; protected internalset; }

2. After two variants of the commissioned wording

In. NET 1.1 we had to declare the method before it was used in the delegate, and after. NET 2.0 we could use anonymous delegates, not only to simplify the notation, but also to access variables within the scope of the anonymous delegate, and then to lambda the expression, which is easier.

1234567891011121314151617181920212223242526272829 classMyClass{    publicdelegatevoidDoSomething(inta);    //定义方法委托    privatevoidDoIt(inta) {        Console.WriteLine(a);    }    privatevoidHowtoDo(DoSomething doMethod,inta) {        doMethod(a);    }    publicstaticvoidMain(string[] args) {        MyClass mc = newMyClass();        //调用定义的方法委托        mc.HowtoDo(newDoSomething(mc.DoIt), 10);        intx = 10;        //使用匿名委托        mc.HowtoDo(delegate(inta){            Console.WriteLine(a + x);        },10);        //使用lamda表达式        mc.HowtoDo(a=>Console.WriteLine(a+x),10);         Console.ReadLine();    }}

3. Declaration of the Collection class

Before we declare a list and assign an initial value to the list, we have to write this:

1234 List<string> list = newList<string>();list.Add("a一");list.Add("b二");list.Add("c三");

You don't need it now, just write it.

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

4. Actions for individual items of a collection class

In order to process the items in the collection individually, we need to write:

1234 foreach(string item inlist){     Console.WriteLine(item);}

I don't need it now, that's it.

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

The code is not refreshing a lot.

5. using = = Try Finally

In order to release resources at the end of use, we often use using,using as a syntactic sugar of try fiannaly. For example

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

The above code can be simplified to:

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

6. The cute Var

The meaning of Var does not have to write the type of declaration, the compiler will judge its type according to the assignment of Var, the type of Var can not be changed once it is confirmed, it can only be used as a local variable, not as a field nor as a parameter declaration.

For example:

1 varwriter = newStreamWriter(path);
1 for(vari=0;i<100;i++){}

7. The evolution of question marks

One of the oldest question marks + colons

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

New baby two question mark??, which represents the left variable if NULL the value is the right variable, otherwise the left variable value

12 stringa = null;varb = a??””;

8. Type-instantiated syntax sugar

12345678 publicclassAbc{    publicintID { get; set; }    publicstring Name { get; set; }    publicstringUrl { get; set; }}

We did not declare the constructor for the class above, but we can instantiate it as in the following form

1234567 public staticvoidMain(string[] args) {        varabc = newAbc{            ID=1,            Name="yukaizhao",            Url="http://yukaizhao.cnblogs.com/"        };    }

9. The legendary extension method

The extension method is introduced in c#3.5, and we can add an instance method to the class without modifying the source of the class, which makes sense. Its essence is also the realization of a kind of grammatical sugar

For example, we extend a Isnumber method to the String class:

1234567891011 public staticclassStringExt {    staticprivateRegex regexNumber = newRegex("\\d+");    staticpublic boolIsNumber(thisstringinput)    {        if(string.IsNullOrEmpty(input))        {            returnfalse;        }        returnregexNumber.IsMatch(input);    }}

We can call this method on a string instance.

12 varabc = “123”;varisNumber = abs.IsNumber();

10. Using anonymous Classes

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

Anonymous classes are useful for returning query data in LINQ to SQL or in the Entity Framework.

If you have more grammar sugar, you are welcome to share it. At the same time I hope you enjoy the grammar of sugar, because he can bring us convenience, please do not sneer at it, there is no need to scoff at it.

Weibo: Http://weibo.com/yukaizhao recommended Shepherd * Red Apricot * Wall classification:. NET development experience, C #, simple problem Tags: csharp, syntax sugar, anonymous delegate, extension method

C # syntax sugar (Csharp syntactic sugar) Grand Summary

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.