Visual C #3.0 overview of new features

Source: Internet
Author: User

After Visual Studio 2005 and C #2.0 are released,MicrosoftThe company repeatedly demonstrated the next generation of C #: C #3.0. Although C #3.0 is not standardized, Microsoft released a preview version at the PDC (professional programmer Conference), so eager programmers can see some of the expected features, this is also the main content discussed in this article:

· Implicit local variables

· Anonymous Variables

· Extension Method

· Object and collection initialization characters

· Lambda expressions

· Query expression

· Expression Tree

  Implicit local variables

C #3.0 introduces a new keyword named "Var ". VaR allows you to declare a new variable. Its type is implicitly inferred from the expression used to initialize the variable. That is to say, the following expression is a valid format:

var i = 1;
This line uses 1 to initialize the variable I. Note that I is strongly typed to an integer. It is not an object or VB6 variable, nor is it loaded with other objects or variables.
To ensure the strong type of variables declared using the VaR keyword, C #3.0 requires that you place the value assignment (initialization) in the same line as the declaration (Declaration. Similarly, the initialization character must be an expression, not an object or collection initialization character, or null. If multiple specifiers exist for the same variable, they must be considered of the same type during compilation.

On the other hand, the implicit type array can use a different format, as shown below:

var intArr = new[] {1,2,3,4} ;
The above line of code declares intarr as int [].

The VaR keyword allows you to use anonymousInstanceTherefore, these instances are static. Therefore, when you create an instance that contains a set of data objects, you do not need to define a class that supports both this structure and data in a static type variable.

  Anonymous variable

C #3.0 allows you to create a class instance flexibly without having to write the class code first. So you can write the code like this:

new {hair="black", skin="green", teethCount=64}
The last line of code, with the help of the New Keyword, creates three types of attributes: hair, skin, and teethcount. In this way, the C # compiler creates a class as follows:

class __Anonymous1
{
 private string _hair = "black";
 private string _skin = "green";
 private int _teeth = 64;
 public string hair {get { return _hair; } set { _hair = value; }}
 public string skin {get { return _skin; } set { _skin = value; }}
 public int teeth {get { return _teeth; } set { _teeth = value; }}
}

In fact, if another anonymous type that meets the same name and type order is created, the compiler will intelligently create only one anonymous type to support two instances. Similarly, Because instances are simple instances of a class, they can be exchanged because the types are actually the same.

Now you have this class, but you still need something to support an instance of the above class. This is the role of the "Var" keyword. It gives you a static instance with more than one anonymous variable. Here is an example of a simple and easy-to-use anonymous type:

var frankenstein = new {hair="black", skin="green", teethCount=64}
  Extension Method

The extension method allows you to use additional static methods to expand various types. However, they are very limited, and can only be used as an alternative when the instance method is insufficient.

An extension method can only be declared in a static class and marked with the keyword "this" placed in the first parameter of the method. The following is an example of a valid extension method:

public static int ToInt32(this string s)
{
 return Convert.ToInt32(s) ;
}

If a static class containing the above methods is introduced using the "using" keyword, The toint32 violation will appear in the existing type (although it is lower than the existing instance method priority ), you can compile and execute the Code as follows:

string s = "1";
int i = s.ToInt32();

This allows you to fully enjoy various built-in or defined type Extension features and add new methods to them.

Object and collection initialization character

C #3.0 is expected to allow you to include an initialization character to specify the initial values of a newly created object or collection. This allows you to combine the Declaration and initialization step by step.

For example, you can define the coordinate class as follows:

public class CoOrdinate
{
 public int x ;
 public int y;
}

You can use an object initialization character to declare and initialize a coordinate object, just like this:

var myCoOrd = new CoOrdinate{ x = 0, y= 0} ;
Maybe you want to ask, why not do it like below?

var myCoOrd = new CoOrdinate(0, 0) ;
Note: I have never declared a constructor for my class that accepts two parameters. In fact, using an object initialization operator to initialize an object is equivalent to calling a non-parameter (default) constructor and assigning values to the relevant amount.

Similarly, in C #3.0, you can easily assign a value to the collection in a more concise way, as shown in the following code of C #2.0:

List animals = new List ();
animals.Add("monkey");
animals.Add("donkey");
animals.Add("cow");
animals.Add("dog");
animals.Add("cat");

Can be shortened:

List animals = new List {"monkey", "donkey", "cow", "dog", "cat" } ;
  Lambda expression: thick coffee with anonymous method

C # 1.x allows you to write code segments in the method. You can use the delegate to call the code easily. Delegation is undoubtedly useful and can be used in any framework. However, in many instances, you must declare a method or a class to use it. Therefore, in order to give you a simpler and more concise encoding method, C #2.0 allows you to use anonymous methods to replace standard calls to delegate. The following code can be seen in. net1.1 or earlier versions:

class Program
{
 delegate void DemoDelegate();
 static void Main(string[] args)
 {
  DemoDelegate myDelegate = new DemoDelegate(SayHi);
  myDelegate();
 }
 void SayHi()
 {
  Console.Writeline("Hiya!!") ;
 }
}

In C #2.0, to use the anonymous method, you must rewrite the Code as follows:

class Program
{
 delegate void DemoDelegate();
 static void Main(string[] args)
 {
  DemoDelegate myDelegate = delegate()
  {
   Console.Writeline("Hiya!!");
  };
  myDelegate();
 }
}

Although the anonymous method takes a further step towards method-based delegate calling, lambda expressions allow you to write anonymous methods in a more concise and functional format.

You can use a Lambda expression as a parameter list to write code, followed by =>, followed by an expression or statement. The above code can be replaced with the following code:

class Program
{
 delegate void DemoDelegate();
 static void Main(string[] args)
 {
  DemoDelegate myDelegate = () =>Console.WriteLine("Hiya!!") ;
  myDelegate();
 }
}

Although lambda expressions are more concise, they are actually a functional superset of anonymous methods. Specifically, lambda expressions provide the following additional functions:

· They allow parameter types to be inferred. The anonymous method requires you to clearly state the status of each type.

· They support Query expressions or C # statements.

· They can be seen as data using the expression tree. This cannot be done using an anonymous method.

  Query expression

This feature allows you to useSQLSimilar statements are also called (LanguageIntegration query ).

For example, you can describe your data as follows:

ublic class CoOrdinate
{
 public int x ;
 public int y;
}

In C #, you can easily declareDatabaseLogical equivalent of a table:

// Use Object and collection initializers
List coords = ... ;

Now, your data can be used as a collection to implement ienumerable. You can easily query data as follows:

var filteredCoords =
from c in coords
where x == 1
select (c.x, c.y)

In the preceding SQL format, "from", "where", and "select" are Query expressions. Some features of C #3.0, such as anonymous type and extension method, are used, implicit local variables. In this way, you can use the SQL format to integrate unrelated data to work together.

Each query expression is actually converted into a C # call, for example:

where x == 1
Will be converted:

coords.where(c =>c.x == 1)
As you can see, this looks like a terrible Lambda expression and extension method. C #3.0 has many other Query expressions and rules about them.

  Expression Tree

C #3.0 contains a new type that allows expressions to be used as runtime data. This type, system. Expressions. Expression Is just a re-expression of a Lambda expression in the memory. The result is that your code can modify and check lambda expressions at runtime.

The following is an example of an Expression Tree:

Expression filter = () =>Console.WriteLine("Hiya!!") ;
Using the expression tree method above, you can use various attributes in the filter variable to check the content of the tree.

  Conclusion

C #3.0 provides some new features that make it easier for you to complete the work of a programmer and architecture designer. It also maintains a rigorous and clear structure of the programming language.

C #3.0 is still in its infancy and will grow up in the next few months, but what it can change is close to its powerful backing.. NET Framework. Its architecture and design model deserve your attention.

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.