In-depth understanding of the five major improvements in C #3.0

Source: Internet
Author: User
1. Hidden local variables

C #3.0 introduces a new keyword named "Var. This keyword allows developers to create a variable without specifying its type. For example, use VaR to describe a string, just like this:

Varmydata = "this is my data ";

Note that the mydata variable is not mentioned here as a string, but C #2.0 requires this.

Although var allows you to create implicit types, it does not reduce the type features of C. The VaR keyword is only useful when you create a variable. Once you create a variable and determine its type, you cannot use VaR to change the type of a variable.

For exampleCodeNo effect:

Varmydate = datetime. now;
Mydate = "hello .";

Using the VaR keyword also produces an interesting result, which helps developers reduce the code input when creating variables. For example, to create a customer object in C #2.0, enter the following code:

Customer mycustomer = new customer ();

To use the new var keyword, you only need to enter:

Varmycustomer = new customer ();

Another feature of the VaR keyword is that it can avoid changing the method call to return a certain type of object. For example, in C #2.0, if you need to call a method to return the customer object, you should write the following code:

Customer mycustomer = getbyname ("Zach ");

If the getbyname method returns an object that is not a customer, this Code cannot be compiled. However, if the VaR keyword is applied, you do not need to worry about the object type returned by getbyname.

Varmydata = getbyname ("Zach ");

Now, because the VaR keyword is applied, the getbyname method can be changed and a person object is returned. This method call is still valid.

2. Extension Method

In C #, you cannot inherit or expand the type marked as "encapsulated" with access identifiers. However, in C #3.0, the extension method allows you to expand any class, or even label it as an encapsulated class. For example, if you want to add a nospaces () method to the string class, you need to define a method similar to the extension method in list.

List

Namespacemyextensionmethods
{
Public static class Extension
{
Public static void nospaces (this string data)
{
Return data. Replace ("","");
}
}
}

When you import this extension method into a class, the developer can call the nosapces () method to any string contained in the class.

The first parameter of the extension method determines the valid type of the extension method. In this case, "this string data" (this string data) indicates that the extension method applies to string classes. If the extension method uses "this object data" (this object data) the first parameter indicates that this method is valid for each object.

To import the extension method, you only need to include a using command in their namespace. For example, to apply the method described above, you need to include a using myextensionmethods command in the class file: (List B)

List B

Usingmyextensionmethods;
Namespace mynamespace
{
Public class myclass
{
Public myclass ()
{
String data = "this is my data ";
// Nospaces will contain "thisismydata ".
String nospaces = data. nospaces ();
}
}
}

Note that the priority of the extension method is lower than that of the instance method. Therefore, if the instance method and the extension method have the same signature, the instance method should be executed.

3. Object initializer

In C #2.0, developers think that many constructors are created to set a property value as the object initialization process. The following is an example: Class access customer method:

Customer mycustomer = new customer ("Zach", "Smith ");

Customer class constructor:

Public customer (string firstname, string lastname): this ()
{
This. firstname = firstname;
This. lastname = lastname;
}

Public customer ()
{}

C #3.0 introduces a new method for initializing objects. It allows you to set any attribute values when initializing objects. For example, in C #3.0, the code block above can be written:

Class access customer method:

Customer mycustomer = new customer {firstname = "Zach", lastname = "Smith "};

Customer class constructor:

Public customer ()
{}

In C #3.0 Code, there is no constructor corresponding to the initialization object. In this way, developers do not need to create different constructors for each set of attributes.

Another result is that the Code is easier to read. For example, although we know that the following code initializes a car object, we do not know the role of the variable:

Car car = new car (18, 10,550 );

At a glance, the following line of code is easier to read, although we must enter more code:

Car car = new car {wheeldiameter = 18, wheelwidth = 10, horsepower = 550 };

4. Anonymous type

C #2.0 introduced the anonymous method, and C #3.0 introduced the anonymous type. The anonymous type is similar to the anonymous method. They are both built in the embedded mode and do not have a formal name. To create an anonymous type, you must combine the above two concepts: Object initializer and hidden local variables. The following is an example of an anonymous type:

Varmytype = new {length = 79, width = 30 };

The range of the anonymous type is the same as that of any other variables. For example, the Cobra instance in the following code block is only valid in the Speed Function Block:

Private void speed ()
{
VaR Cobra = new {horsepower = 550, torque = 570 };
}

If an anonymous type is initialized and another anonymous type is in the range domain, and their signatures are the same, the second type occupies the first type. For example, in the following code, Cobra and Mustang are both anonymous and can be set to each other.

Private void speed ()
{
VaR Cobra = new {horsepower = 550, torque = 570 };
VaR Mustang = new {horsepower = 300, torque = 300 };
Mustang = Cobra; // or you cocould say Cobra = mustang
}

5. LINQ

In the previous C # version, developers used many different query languages to access different data sources. For example, to query an XML file, the developer will use XPath. to query a SQL database, the developer will use SQL. In the past, this method was very effective and is still the main method for accessing various data. However, this method has some disadvantages. A major drawback is that developers must write query code in a different language rather than the language they are currently using (such as SQL or XPath. Another drawback is that when executing some query languages, such as SQL, the developer must write the ing code to convert the query results into available C # business objects.

C #3.0 introduces a new method called Language Integrated Query (LINQ. With the application of LINQ, developers can compile code that can search for any ienumerable <t> data source. Therefore, in addition to using tsql to access the ms SQL database, and using XPath to access XML files, they can also use LINQ.

The following code (List C) is an example of a LINQ query, which returns all customers whose ordercount is greater than 10:

List C

Using system;
Using system. query;
Using system. Collections. Generic;

Public class sampleclass
{
Static void main ()
{
List <customer> MERs = getcustomers ();
// Write our query to retrieve MERs mers who have more
// 10 orders.
Ienumerable <customer> queryresult = from customer in mers MERs
Where customer. ordercount> 10
Orderbycustomer. ID
Select customer;
}
}

Unlike SQL or XPath, LINQ queries are written in C # rather than a third-party language. In this way, there will be no type issues in the query, and developers do not need to write the ing code to convert the data returned by the query into a C # object, and the LINQ ing is automatically processed by the linq api.

Basically, in the orm solution, the LINQ object is very useful. Similarly, it is widely used and has a large amount of msdm information describing its functions. For more information, visit the LINQ homepage.

URL: http://dev.yesky.com/msdn/35/2707535.shtml

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.