C # 3.0 new feature creation and initialization collection objects

Source: Internet
Author: User
Tags command line mscorlib query reference visual studio
Create | objects | collections

   first, the introduction

The new object initializer in C # 3.0 is a simple syntax feature that enables the construction and initialization of objects to be very simple. Suppose you have a class student that looks something like this:

public class student{
public string FirstName;
public string LastName;
}
So, you can use the object initializer to create an object of this class, as follows:

var student1 = new Student{firstname = "Bruce", LastName = "Willis"};
The new collection initializer syntax in C # 3.0 also has similar operational characteristics. For example, any object that implements System.Collections.Generic.ICollection <T> can initialize its value using a collection initializer.

A collection initializer consists of the following parts:

· An object initializer sequence, included with the "{" and "}" symbols, and separated by commas.

· Element initializers, each of which specifies an element to be added to the specified collection object (the element initializer cannot be an assignment expression in a collection initializer).

So, how exactly does it work? A collection initializer must follow the following rules:

· Each collection object that applies a collection initializer must be a type that implements the System.Collections.Generic.ICollection <T> (exactly one T).

· There must be an implicit conversion from each element initializer to the T type. A collection initializer calls the ICollection <T>. ADD (T) method in sequence for each specified element.

As an example, the following collection initializer creates and initializes a new collection of strings-this collection has 3 members: "Alice", "Bob" and "Chris", as follows:

List <string> names = new list <string> {"Alice", "Bob", "Chris"};
Note: All of the initial values are string types. Otherwise, you will get a compiler error.

   II. Implementation of Set initialization

Suppose you want to describe a class and a registered classmate in it. To do this, you can programmatically implement this by using the collection initializer in C # 3.0, as follows:

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.query;
Using System.Xml.XLinq;
Using System.Data.DLinq;
Namespace Collectioninitializer
{
Class Program
{
public class MyClass
{
public string Nameofclass;
Public List <string> studentnames = new list <string> ();
}
static void Main (string[] args)
{
var classes = new List <MyClass>
{
New MyClass
{
Nameofclass = "Science",
Studentnames = {"Laura", "George"}
},
New MyClass
{
Nameofclass = "Commerce",
Studentnames = {"Bill", "Hillary"}
}
};
}
}
}
If you have Visual Studio 2005 and you have a LINQ Preview installed, you can compile the code above in the IDE.

If you do not have vs 2005 but have LINQ Preview installed, you can use the following command to compile the code from the command line:

C:\Program files\linq Preview\bin\csc.exe
/reference: "C:\Program files\linq Preview\bin\system.data.dlinq.dll"
/reference:c:\windows\microsoft.net\framework\v2.0.50727\system.data.dll
/reference:c:\windows\microsoft.net\framework\v2.0.50727\system.dll
/reference: "C:\Program files\linq Preview\bin\system.query.dll"
/reference:c:\windows\microsoft.net\framework\v2.0.50727\system.xml.dll
/reference: "C:\Program files\linq Preview\bin\system.xml.xlinq.dll" Program.cs

   Three, code analysis

Let's analyze the previous C # 3.0 code in more detail:

var classes = new List <MyClass>
{
New MyClass
{
Nameofclass = "Science",
Studentnames = {"Laura", "George"}
},
New MyClass
{
Nameofclass = "Commerce",
Studentnames = {"Bill", "Hillary"}
}
};
For the compiler, it has the same effect as the following code:

var classes = new List <MyClass> ();
var __c1 = new MyClass ();
__c1.nameofclass = "Science";
__c1.studentnames.add ("Laura");
__c1.studentnames.add ("George");
Classes. ADD (__C1);
var __c2 = new MyClass ();
__c2.nameofclass = "Commerce";
__c2.studentnames.add ("Bill");
__c2.studentnames.add ("Hillary");
Classes. ADD (__C2);
If the ILDASM is activated and the compiled binary code is turned on, you can see something like Figure 1.


Figure 1. Binary form of compilation of sample code fragments
If you double-click the main node in the ILDASM, you will see the following code:

. method private Hidebysig static void Main (string[] args) cil managed
{
. entrypoint
Code size 138 (0X8A)
. maxstack 3
. Locals init ([0] class [mscorlib]system.collections.generic.list ' 1
<class collectioninitializer.program/myclass>
Classes
[1] class [mscorlib]system.collections.generic.list ' 1
<class collectioninitializer.program/myclass>
' <tampa> f__0 ',
[2] class Collectioninitializer.program/myclass
' <tampa> f__1 ',
[3] class Collectioninitializer.program/myclass
' <tampa> f__2 ')
Il_0000:nop
Il_0001:nop
Il_0002:newobj instance void class [Mscorlib]system.collections.
Generic.list ' 1<class Collectioninitializer.
Program/myclass>::.ctor ()
Il_0007:stloc.1
Il_0008:ldloc.1
Il_0009:nop
il_000a:newobj instance void Collectioninitializer.
Program/myclass::.ctor ()
Il_000f:stloc.2
Il_0010:ldloc.2
Il_0011:ldstr "Science"
IL_0016:STFLD string Collectioninitializer.
Program/myclass::nameofclass
Il_001b:nop
Il_001c:ldloc.2
IL_001D:LDFLD class [Mscorlib]system.collections.generic.list ' 1
<string> Collectioninitializer.
Program/myclass::studentnames
Il_0022:ldstr "Laura"
Il_0027:callvirt instance void class [Mscorlib]system.
Collections.Generic.List ' 1 <string>:: Add (!0)
Il_002c:nop
Il_002d:ldloc.2
IL_002E:LDFLD class [Mscorlib]system.collections.generic.list ' 1
<string> Collectioninitializer.
Program/myclass::studentnames
Il_0033:ldstr "George"
Il_0038:callvirt instance void class [Mscorlib]system.collections.
Generic.list ' 1 <string>:: Add (!0)
Il_003d:nop
Il_003e:nop
Il_003f:ldloc.2
Il_0040:nop
Il_0041:callvirt instance void class [Mscorlib]system.collections.
Generic.list ' 1<class Collectioninitializer.
Program/myclass>::add (!0)
Il_0046:nop
Il_0047:ldloc.1
Il_0048:nop
il_0049:newobj instance void Collectioninitializer.
Program/myclass::.ctor ()
Il_004e:stloc.3
Il_004f:ldloc.3
Il_0050:ldstr "Commerce"
IL_0055:STFLD string Collectioninitializer.
Program/myclass::nameofclass
Il_005a:nop
Il_005b:ldloc.3
IL_005C:LDFLD class [Mscorlib]system.collections.generic.list ' 1
<string> Collectioninitializer.
Program/myclass::studentnames
Il_0061:ldstr "Bill"
Il_0066:callvirt instance void class [Mscorlib]system.collections.
Generic.list ' 1 <string>:: Add (!0)
Il_006b:nop
Il_006c:ldloc.3
IL_006D:LDFLD class [Mscorlib]system.collections.generic.list ' 1
<string> Collectioninitializer.
Program/myclass::studentnames
Il_0072:ldstr "Hillary"
Il_0077:callvirt instance void class [Mscorlib]system.collections.
Generic.list ' 1 <string>:: Add (!0)
Il_007c:nop
Il_007d:nop
Il_007e:ldloc.3
Il_007f:nop
Il_0080:callvirt instance void class [Mscorlib]system.collections.
Generic.list ' 1<class Collectioninitializer.
Program/myclass>::add (!0)
Il_0085:nop
Il_0086:ldloc.1
Il_0087:nop
il_0088:stloc.0
Il_0089:ret
}//program::main Method End
   Iv. Summary

As you can see from some of the previous snippets, C # 3.0 has taken a big step in syntax.

The collection initializer, as one of the newly introduced features of C # 3.0, provides a new syntax for initializing collection objects. This simple syntax combines the creation and initialization of a collection object into one step.

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.