C # 3.0 new features Overview

Source: Internet
Author: User
Tags anonymous instance method static class
1. Visual C # 3.0 new features Overview

After publishing visual Studio 2005 and c#2.0, Microsoft has been on a non-stop display of the expected next-generation version of C #: C # 3.0. Although C # 3.0 is not standardized, Microsoft has released a preview version at the PDC (Professional Programmer's meeting), so impatient programmers can see some of the desired features, which is the main topic of this article:

• Implicitly typed Local variables

• Anonymous variables

• Extension methods

• Object and collection initialization characters

· Lambda expression

• Query expressions

• Expression tree

Implicitly typed Local variables

C # 3.0 introduces a new keyword called "Var". var allows you to declare a new variable whose type is implicitly inferred from an expression used to initialize the variable. In other words, the following expression is a valid format:

var i = 1;

This line uses one of the first initializer variables I. Note that I is strongly typed to an integral type, it is not an object or a VB6 variable, nor is it loaded with other objects or variables.
To guarantee the strongly typed nature of variables declared using the var keyword, c#3.0 requires that you place the assignment (the initializer) in the same row as the Declaration (Declaration). Similarly, the initializer must be an expression and cannot be an object or a collection initializer or null. If multiple declarations exist for the same variable, they must be treated as the same type at compile time.

An implicitly-typed array, on the other hand, can use a different format, as follows:

var intarr = new[] {1,2,3,4};

The code in the previous line will declare Intarr as int[].

The var keyword allows you to use instances of anonymous types, so these instances are static types. So, when you create an instance of an object that contains a set of data, you don't have to define a class to support both the structure and the data in a static type variable.

Anonymous variable

C # 3.0 gives you the flexibility to create an instance of a class without having to write the code for that class first. So you can write code like this:

New {hair= "black", skin= "green", teethcount=64}

The previous line of code, with the help of the new keyword, created a three-attribute type: Hair,skin and Teethcount. The C # compiler then creates a class that looks like this:

Class __anonymous1
{
private string _hair = "BLACK";
private string _skin = "green";
private int _teeth = 64;
public string Hair {get {_hair;} set {_hair = value;}}
public string Skin {get {_skin;} set {_skin = value;}}
public int Teeth {get {_teeth;} set {_teeth = value;}}
}

In fact, if another anonymous type that satisfies the same name and type Order is created, the compiler will also be smart enough to create only one anonymous type to support two instances to use. Similarly, because instances are simple instances of a class, they can be interchanged because the type is 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 lets you have a static type instance of more than one instance of an anonymous variable. Here's an example of a simple, Easy-to-use anonymous type:

var Frankenstein = new {hair= "black", skin= "green", teethcount=64}


Extension methods

Extension methods enable you to use additional static methods to extend various types. However, they are very limited and can only be used as alternates if the instance method is not sufficient.

An extension method can only be declared in a static class, and the keyword "This" is placed in the first parameter of the method to identify, as follows is an example of an effective 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 offense will appear in the existing type (although it is less priority than the current instance method), you can compile and execute the code like this:

string s = "1";
int i = S.toint32 ();


This allows you to fully enjoy the extended features of a variety of built-in or defined types, and to add new methods to them.


Object and collection initialization characters

C # 3.0 is expected to allow you to include an initializer that specifies the initial value of a newly created object or collection. This allows you to combine declaration and initialization in one step.

For example, you can define coordinate classes like this:

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

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

var Mycoord = new coordinate{x = 0, y= 0};

Maybe you should ask, why don't you do it like this.

var mycoord = new Coordinate (0, 0);

Note: I have never declared a constructor that accepts two arguments for my class. In fact, initializing an object with an object initializer is equivalent to calling a parameterless (default) constructor and assigning a value to the related quantity.

Similarly, in c#3.0 you can easily assign values to collection in a more concise way, such as the following code for C # 2.0:

list<string> animals = new list<string> ();
Animals. ADD ("monkey");
Animals. Add ("donkey");
Animals. ADD ("cow");
Animals. Add ("dog");
Animals. ADD ("Cat");
can be shortened to:


list<string> animals = new List<string> {"Monkey", "Donkey", "cow", "dog", "Cat"};

Lambda expression: Anonymous method of espresso

C # 1.X allows you to write code snippets in a method that you can easily invoke using a delegate (delegate). A delegate is undoubtedly useful and can be used arbitrarily in a framework, but in many instances you must declare a method or a class in order to use it. Therefore, to give you an easier and simpler way to encode, C # 2.0 allows you to replace standard calls to delegates with anonymous methods. The following code can be used in the. NET1.1 or earlier versions see:


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, using anonymous methods, you have to rewrite the code like this:

Class Program
{
delegate void Demodelegate ();
static void Main (string[] args)
{
Demodelegate mydelegate = Delegate ()
{
Console.WriteLine ("hiya!!");
};
MyDelegate ();
}
}
Although anonymous methods are a step closer to a method-based delegate invocation, lambda expressions allow you to write anonymous methods in a more concise, functional format.

You can write a lambda expression as a list of parameters, 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. In particular, lambda expressions provide the following additional functionality:

• They allow parameter types to be inferred. Anonymous methods require you to clearly state each type.

• They can support query expressions or C # statements.

• They can be considered as data using an expression tree. This is not an anonymous method to do.

Query expression

This feature allows you to use SQL-like-style statements in C #, also known as LINQ (language integration Queries).

For example, you can describe your data in this way:

Ublic class Coordinate
{
public int x;
public int y;
}

In C #, you can declare the logical equivalence of a database table as easily as the following:

Use Object and collection initializers
list<coordinate> coords = ...;
Now your data can be implemented as a collection ienumerable<t&gt, and you can easily query the data as follows:

var filteredcoords =
From C in coords
where x = = 1
Select (c.x, C.Y)

In the above SQL-style format, "from", "where," and "select" are query expressions that use some of the features of C # 3.0 such as anonymous types, extension methods, implicitly typed local variables, and so on. This way, you can use the SQL-style format to work with data integration that is not connected.

Each query expression actually turns into a call to a C #, such as:

where x = = 1

will be converted to:

Coords.where (c => c.x = 1)

As you can see, this looks a lot like a scary lambda expression and extension method. C # 3.0 also has a lot of other query expressions and rules about them.

An expression tree

C # 3.0 contains a new type that allows an expression to be used as run-time data. This type,system.expressions.expression< t&gt, just a new expression of a lambda expression in memory. The result is that your code can modify and check lambda expressions at run time.

The following is an example of an expression tree:

expression<demodelegate> filter = () => Console.WriteLine ("hiya!!");


Using a method like the expression tree above, you can use the various properties in the filter variable to check the contents of the tree.

Conclusion

C # 3.0 provides some new features that make it easier for you to work with a programmer and architect, while maintaining a rigorous and clear structure of the programming language.

C # 3.0 is still in its infancy and will grow in the coming months, but everything it can change is close to its powerful backing. NET Framework, its architecture and design patterns, worthy of your attention.

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.