New features for C # versions

Source: Internet
Author: User
Tags static class

C # 2.0

Generics (generics)

Generics are the most important new features introduced in CLR 2.0, making it possible to parameterize the types used in classes and methods.

For example, a generic class is defined here:

Class Mycollection<t> {t variable1; private void Add (t param) {}}

When used:mycollection<string> List2 = new mycollection<string> (); mycollection<object> list3 = new mycollection<object> ();

Benefits of generics when compiling, you can guarantee type safety do not have to do type to replace, to obtain a certain performance improvement

Generic methods, generic delegates, generic interfaces

In addition to generic classes, there are generic methods, generic delegates, and generic interfaces:

Generic delegate public static delegate T1 Mydelegate<t1, t2> (T2 item); Mydelegate<int32, string> MyFunc = new Mydelegate<int32, string> (SOMEMETHD); Generic interface public class MYCLASS<T1, T2, t3>: Myinteface<t1, T2, t3> {public T1 Method1 (T2 param1, T3 param2) {T Hrow new NotImplementedException (); } interface Myinteface<t1, T2, t3> {T1 Method1 (T2 param1, T3 param2);

generic method static void swap<t> (ref T T1, ref t T2) {T temp = t1; t1 = t2; t2 = temp;} String str1 = "a"; String str2 = "B"; Swap<string> (ref str1, ref str2);

Generic constraint (constraints)
You can add constraints to the type parameters of a generic type, and you can require these type parameters to satisfy a certain condition

Constraints

Description

where t:struct Type arguments need to be value types
where T:class Type parameter needs to be a reference type
where T:new () The type parameter must have a public parameterless constructor
Where T: <base class name> Type parameter to derive from a base class
where T: <interface name> The type parameter implements an interface
where T:u where T and u are all type parameters, T must be or derive from U

These constraints can be used together at the same time:

Class employeelist<t> where T:employee, IEmployee, System.icomparable<t>, new () {//...}

Default keyword

This key can be used on the type parameter:

Default (T);

For a value type, returns 0, a reference type, returns NULL, and for a struct type, returns a struct instance with a member value of all 0.

Iterator (iterator)

You can use a foreach statement without implementing IEnumerable, and it automatically generates methods of IEnumerable interfaces when the compiler encounters a yield return. In the method or property that implements the iterator, the return type must be IEnumerable, IEnumerator, Ienumerable<t>, or ienumerator<t>. Iterators make it easy to traverse some fragmented data without having to implement current and MoveNext these methods.

Public System.Collections.IEnumerator GetEnumerator () {yield return-1;? (int i = 1; i < Max; i++) {yield return I ; } }

Nullable type (Nullable type)

Nullable types are system.nullable<t> nullable types are only for value types and cannot be created for reference types. System.nullable<t> is abbreviated to T?.

Int? num = null; if (Num. HasValue = = True) {System.Console.WriteLine ("num =" + num.) Value); else {System.Console.WriteLine ("num = Null");}

If HasValue is false, an exception is thrown when the value is used. Assign a nullable variable x to a variable y that is not nullable can be written like this:

int y = x?? -1;

Anonymous methods (Anonymous method)

Before c#2.0, a delegate can only be created with a declared good method. Once you have an anonymous method, you can pass a code block when you create the delegate.

delegate void Del (int x); Del d = delegate (int k) {/* ... */}; System.Threading.Thread T1 = new System.Threading.Thread (delegate () {System.Console.Write ("Hello,");}); Simplification of the delegate syntax//C # 1.0 writing ThreadStart ts1 = new ThreadStart (METHOD1); C # 2.0 can write ThreadStart ts2 = Method1;

Covariance and contravariance of delegates (covariance and contravariance)

There are two classes below:

Class Parent {} class Child:parent {}

Then look at the following two delegates:

Public delegate Parent Delgparent ();

Public delegate child Delgchild ();

public static Parent Method1 () {return null;}

public static Child Method2 () {return null;}

static void Main () {delgparent del1= Method1; Delgchild del2= Method2; Del1 = Del2; }

Notice that delgparent and delgchild are completely different types, and they don't have any inheritance relationships, so theoretically they can't be assigned to each other. But because of the covariant relationship, we can assign the delegate of the Delgchild type to the Delgparent type delegate. Covariance for the return value of the delegate, the inverse of the argument, the principle is the same.

Partial class (partial)

When declaring a class, struct, or interface, use the partial keyword to distribute the source code in a different file. I think it's really not much of a practical use to take care of the functionality introduced by ASP.net code separation. Microsoft said that in some big projects can separate the classes in different files for different people to achieve, to facilitate teamwork, which I think is pure nonsense.

Some classes are just compiler-provided functionality that, when compiled, compiles the classes defined by the partial keyword with the CRL, and does not have anything to do with CRLs.

Static Class (Statics Class)

A static class is a class that can have only static members, and a class is marked with the static keyword, which cannot be instantiated. Static classes are theoretically equivalent to a generic class that has only static members and constructors are private, and the relative advantage of static classes is that the compiler can guarantee that static classes do not add any non-static members.

Global::

This represents the global namespace (the top-level namespace), which is the default namespace for any program.

Class TestApp {public class System {} const int Console = 7; static void Main () {//error with this access, System and Console are both occupied//cons Ole. WriteLine (number); Global::system.console.writeline (number); } }

extern Alias

A conflict that eliminates duplicate class names in different assemblies, which can refer to different versions of the same assembly, that is, at compile time, providing a means to differentiate conflicting assemblies.

At compile time, use command-line arguments to indicate the alias, for example:

/r:aliasname=assembly1.dll

In Visual Studio, you can specify the value of the alias in the properties of the referenced assembly, which is global by default.

And then you can use it in the code:

extern alias AliasName; This line needs to be in the front using System of the using these statements; Using System.Collections.Generic; Using System.Text; Using Aliasname.xxx;

Attribute accessor access control

public virtual int TestProperty {protected set {} get {return 0;}}

Buddy Assembly (Friend Assembly)

You can have other assemblies access your internal members (private or not) and use attributes to implement them, for example:

[Assembly:internalsvisibleto ("cs_friend_assemblies_2")]

Note that this scope is the entire assembly.

Fixed key word

You can use the fixed keyword to create a fixed-length array, but the array can only be one of bool, Byte, char, short, int, long, sbyte, ushort, uint, ulong, float, double.

This is mainly for the better handling of some unmanaged code. For example, the following structure:

public struct MyArray {public fixed char pathname[128];}

Without fixed, it is not possible to take up 128 char space in advance, and use fixed to interact with unmanaged code.

volatile keyword

Used to indicate that related words may be accessed by multiple threads at the same time, the compiler does not perform a single-threaded optimization on the corresponding values, guaranteeing that the associated values are up-to-date at all times.

#pragma warning

Used to cancel or add a compile-time warning message. Each warning message will have a number, if warning CS01016 and the like, use the number after the CS, for example:

#pragma warning Disable 414, 3021

So the warning messages for CS414 and CS3021 are not displayed.

C # 3.0

Type inference

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.