LINQ experience (2) -- C #3.0 new language features and improvements (Part 1)

Source: Internet
Author: User

In the first article, I learned about the new features of Visual Studio 2008. Starting from this article, I went to the second part of this series to introduce the features and improvements of C #3.0.

In general, Visual Studio 2008 and. net 3.5 is built on. based on the core of net2.0 ,. the core of net2.0 will not change. for more information about net2.0, see msdn or some classic books. based on net2.0, these improved functions can greatly simplify programming. Many of my friends on the blog of C #3.0 introduced the new language features. Here I will give a brief introduction, record what I learned, and lay the foundation for the subsequent LINQ.

C #3.0 new language features and improvements include:

  • Auto-implemented Properties)
  • Local variable type inference)
  • Anonymous type (anonymous types)
  • Object and collection initializers)
  • Extension methods)
  • Lambda expression and Lambda Expression Tree (lambda expression and Lambda expression trees)
Auto-implemented Properties)

Automatic attributes can avoid manually declaring a private member variable and writing the get/set logic. In vs2008, you can write a class as follows, the compiler automatically generates private variables and default get/set operations. You can also define access levels such as get and set "protected.

In the. net2.0 framework, we can write a user class like this:

public class User{    private int _id;    private string _name;    private int _age;    public int Id   {        get { return _id; }        set { _id = value; }   }    public string Name     {        get { return _name; }        set { _name = value; }    }    public int Age     {        get { return _age; }        set { _age = value; }     }}

Now, you can simplify the process as follows:

public class User{    public int Id { get; set; }    public string Name { get; set; }    public int Age { get; set; }}

If the empty GET/set attribute like above is used, it will automatically generate a private member variable for you in the class and implement a public getter and setter for this variable. We can use the ildasm.exe (IL code reassembler) tool provided by the .net development environment to analyze the content of an assembly or module. I will not map any more.

Local variable type inference)

C #3.0 introduces the New Keyword var, which can be used to replace the original type name when declaring a local variable, that is, when a variable Declaration identifies the VaR type and there is no var name type in the range field, this declaration is called an implicit type local variable. As follows (equivalent to the explicit declaration following ):

var i = 5;//intvar j = 23.56;//doublevar k = "C Sharp";//stringvar x;// ╳var y = null;//╳var z = { 1, 2, 3 };//╳

In the debugging status, the compiler explains the following:

Key Points of implicit local variables

  1. VaR is the keyword and can be automatically inferred based on the subsequent initialization statement. This type is strongly typed.
  2. The initialization statement must be an expression and cannot be empty. The types can be inferred during compilation. Once initialized, only this type can be stored.
  3. VaR declares only local variables and cannot be used for fields. It can also be used in for, foreach, using, and other statements.
  4. Arrays can also be used as implicit types.
  5. An initialization statement cannot be an object or a set initializer, but it can be a new expression that contains an object or an object.
  6. If the local variable Declaration contains multiple declarers, the types must be the same.
Anonymous type (anonymous types)

The anonymous type allows you to define the intra-row type without explicitly defining the type. It is often used with VAR to declare the anonymous type.

VaR p1 = new {id = 1, name = "yjinglee", age = 22}; // you do not need to declare the property var P2 = new {id = 2, name = "xieqing", age = 25}; P1 = P2; // P1, P2 has the same structure and can be assigned to each other

Here the compiler will think that P1 and P2 are equivalent:

public class SomeType{     public int Id { get; set; }     public string Name { get; set; }     public int Age { get; set; }}

How can an array be defined? Use the "new []" keyword to declare the array and add the array's Initial Value List. Like this:

var intArray = new[] { 2, 3, 5, 6 };var strArray = new[] { "Hello", "World" };var anonymousTypeArray = new[] { new { Name = "YJingLee", Age = 22 }, new { Name = "XieQing", Age = 25 } };var a = intArray[0];var b = strArray[0];var c = anonymousTypeArray[1].Name;

Key points of the anonymous type

  1. You can use the new keyword to call the anonymous initiatorto create an anonymous object.
  2. The anonymous type is directly inherited from system. object.
  3. Anonymous members are some of the read/write attributes inferred by the compiler based on the initialization tool.
Object and collection initializers object initializers ):

The type in the. net2.0 framework is very dependent on attributes. When an object instance is generated and a new type is used, we write it like this in. net2.0:

User user = new User();user.Id = 1;user.Name = "YJingLee";user.Age = 22;

In vs2008, the compiler automatically generates the appropriate property setter code, so that the original attribute assignment operations can be completed in one row. We can simplify it like this: like this,The object initializer is composed of a series of member objects, whose objects must be initialized and closed with commas.

User user = new User { Id = 1, Name = "YJingLee", Age = 22 };

For example, I add two persons to a list set of user-based generic types:

List<User> user = new List<User>{        new User{Id=1,Name="YJingLee",Age=22},        new User{Id=2,Name="XieQing",Age=25},};

If two object initiators with the same name and type generate the same instance, they can assign values to each other. For example:

User user = new User { Id = 1, Name = "YJingLee", Age = 22 };User user2 = new User { Id = 2, Name = "XieQing", Age = 25 };user = user2; 

In addition to setting simple attribute values during class initialization, the object initialization feature also allows us to set more complex nested attribute types. For example, we can have an attribute named "Address" belonging to the address type in the user type defined above:

User user = new User{      Id = 1,     Name = "YJingLee",     Age = 22,     Address = new Address     {          City = "NanJing",          Zip = 21000     }};
Collection initializers ):

The Set initiator is composed of a series of set objects separated by commas (,) and closed.
The Set initialization tool can simplify adding several objects together to a set. The compiler will automatically Insert the set for you. For example, I add seven numbers to a list set of generic type Int.

List<int> num = new List<int> { 0, 1, 2, 6, 7, 8, 9 };

Key Points of object and set Initiators

  1. The object initializer actually uses the compiler to assign values to externally visible fields and attributes of the object in order.
  2. The object initializer allows only assigning values to some attributes, including the internal access level.
  3. The object initializer can be used together with the constructor, And the constructor initializes the object before it executes.
  4. The collection initializer calls the icollection <t>. Add (t) method in sequence for the elements in the initialization tool.
  5. Pay attention to the visibility and call sequence of the members in the object initiator and set initiator.
  6. The object is also a compilation technology with the set initiator.

This is the first time. For more information, see from: Li yongjing.

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.