Deep understanding of the five major improvements in C # 3.0

Source: Internet
Author: User
Tags anonymous extend sql variables static class variable valid access
1. Implicit local variables

C # 3.0 introduces a new keyword called "var". This keyword allows the developer to create a variable, but does not have to be explicit about its type. For example, use Var to describe a string, like this:

Varmydata = "This is my data";
Note that there is no mention that the MyData variable is a string, and C # 2.0 asks for it.

Although Var allows you to create an implied type, it does not degrade C # 's strong type characteristics. The VAR keyword is only useful when creating a variable, and once you have established the variable and determined its type, you cannot use Var to change the type of the variable.

For example, this code does not work:

Varmydate = DateTime.Now;
MyDate = "Hello.";
Using the VAR keyword also produces an interesting result that can help developers reduce the code input when creating variables. For example, to create a customer object in C # 2.0, you would enter the following code:

Customer MyCustomer = new Customer ();
With the new var keyword, simply enter:

Varmycustomer = new Customer ();

Another feature of the Var keyword is that it avoids changing a method call that returns a type object. For example, in C # 2.0, if you need to call a method that returns a Customer object, you should write the following code:

Customer MyCustomer = Getbyname ("Zach");
If a Getbyname method returns an object that is not a customer at some point, the code cannot be compiled. However, if you apply the var keyword, you do not have to worry about the type of object returned by Getbyname.

Varmydata = Getbyname ("Zach");
Now, because the VAR keyword is applied, the Getbyname method can be changed to return a person object, and this method call is still valid.

2.extension method

In C #, you cannot inherit and extend a type marked as "encapsulated" with an access identifier. But in C # 3.0, the extension method allows you to extend any class, even a class that is marked as encapsulated. For example, if you want to add a nospaces () method to a string class, we want to define a extension method similar to the one in List A.

List A

Namespacemyextensionmethods
{
public static Class Extension
{
public static void Nospaces (this string data)
{
return data. Replace ("", "");
}
}
}
When you import this extension method in a class, the developer is able to invoke the Nosapces () method on any string that the class contains.

The first parameter of the extension method determines the valid type of the extension method. In this case, this string data indicates that the extension method applies to the String class, and if the extension method takes "this object data" as the first argument, Indicates that this method is valid for each object.

To indicate that you want to import the extension method, simply include a using directive in their namespaces. For example, to apply the method described above, you need to include a using Myextensionmethods directive in the class file: (List B)

List B

Usingmyextensionmethods;
Namespace MyNamespace
{
public class MyClass
{
Public MyClass ()
{
String data = "This is my data";
Nospaces would contain "Thisismydata".
String nospaces = data. Nospaces ();
}
}
}


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

3. Object initializers

In C # 2.0, developers believe that a number of constructors are set up to set a property value as an object initialization process. Here's an example: class accesses the Customer method:

Customer MyCustomer = new Customer ("Zach", "Smith");
Customer Class Builder:

Public Customer (String firstName, String lastName): this ()
{
This. FirstName = FirstName;
This. LastName = LastName;
}

Public Customer ()
{}
C # 3.0 introduces a new method of initializing an object, which allows you to set any property values when initializing an object. For example, in C # 3.0, the above code block can be written as:

class to access the customer method:

Customer MyCustomer = new Customer{firstname = "Zach", LastName = "Smith"};
Customer Class Builder:

Public Customer ()
{}
In the C # 3.0 code, there is no constructor corresponding to the initialization object. In this way, developers do not have to create different constructors for each set of attributes that need to be set.

Another effect of this is that the code becomes easier to read. For example, although we know clearly that the following code initializes a car object, we do not know the function of the variable:

Car car = new car (18, 10, 550);
At first glance, the following line of code is easier to read, although we have to enter more code:

Car car = new Car {wheeldiameter = Wheelwidth = ten, horsepower = 550};
4. Anonymous type

C # 2.0 introduces an anonymous method, and C # 3.0 launches an anonymous type. Anonymous types are similar to anonymous methods, and they are all built in embedded mode with no formal name. In establishing an anonymous type, you must combine the concepts of the above object initializers and implicit local variables. The following is an example of an anonymous type:

Varmytype = new {Length = +, Width = 30};
The scope of an anonymous type is the same as that of any other variable. For example, the Cobra instance in the following code block is valid only in the SPEED function block:

private void Speed ()
{
var Cobra = new {horsepower = Torque = 570};
}
If an anonymous type is initialized and another anonymous type is in the scope domain, and their signatures are the same, the second type consumes itself the type of the first type. For example, in the following code, Cobra and Mustang are anonymous types and can be set for each other.

private void Speed ()
{
var Cobra = new {horsepower = Torque = 570};
var Mustang = new {horsepower = $, Torque = 300};
Mustang = Cobra; Or you could 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 would use XPath to query a SQL database, and the developer would use SQL. This approach has been effective in the past and is still the main way to access the various data. However, this approach has some drawbacks. A notable drawback is that developers must write query code in a different language than the language they are currently using, such as SQL or XPath. Another disadvantage is that when executing some query languages, such as SQL, the developer must write mapping code to translate the query results into usable C # business objects.

C#3.0 introduces a new approach called language-Integrated Query (LINQ). Using LINQ, developers can write code that can search any ienumerable<t> data source. So in addition to using TSQL to access the MS SQL database, applying XPath to access the XML files, they can also apply LINQ.

The following code (list C) is an example of a LINQ query that returns all customers with OrderCount greater than 10:

List C

Using System;
Using System.query;
Using System.Collections.Generic;

public class SampleClass
{
static void Main ()
{
List<customer> customers = GetCustomers ();
Write our query to retrieve customers who have more than
Ten orders.
Ienumerable<customer> QueryResult = from Customer in Customers
where customer. OrderCount > 10
Orderbycustomer.id
Select customer;
}
}
Unlike SQL or XPath, LINQ queries are written in C #, not in third-party languages. This way, the query does not have a type problem, and the developer has no need to write mapping code to convert the data returned by the query into a C # object, and the LINQ API automatically processes the mappings.

Basically, LINQ objects use a lot of ORM solutions. Similarly, it has a wide range of MSDM information describing its functions. For more information, please visit the LINQ home page.



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.