C # Common Language sugars (Csharp syntactic sugar)

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

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

public string MyName {get; set;}

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

public string MyName {get; protected internal set;}

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.

Class MyClass

{

public delegate void DoSomething (int a);

Defining method delegates

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 ();

Invoking a defined method delegate

Mc. Howtodo (New DoSomething (MC. DoIt), 10);

int x = 10;

Using anonymous delegates

Mc. Howtodo (delegate (int a) {

Console.WriteLine (a + x);

},10);

Using LAMDA expressions

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:

list<string> list = new list<string> ();

List. ADD ("a One");

List. ADD ("b two");

List. ADD ("C three");

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

list<string> list = new List<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:

foreach (string item in list)

{

Console.WriteLine (item);

}

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

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

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 to:

using (var sw = new StreamWriter ("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:

var writer = new StreamWriter (path);

for (Var i=0;i<100;i++) {}

7 . The evolution of question marks

One of the oldest question marks + colons

var B = 3;

var a = 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

string a = null;

var B = A?? "";

8 . Type- instantiated syntax sugar

public class ABC

{

public int ID {get; set;}

public string Name {get; set;}

public string Url {get; set;}

}

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

public static void Main (string[] args) {

var abc = new abc{

Id=1,

Name= "Yukaizhao",

Url= ""

};

}

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:

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 a string instance.

var abc = "123";

var isnumber = abs. Isnumber ();

10. Using anonymous Classes

var a = 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.

C # Common Language sugars (Csharp syntactic sugar)

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.