C #3.0 new syntax features

Source: Internet
Author: User

Implicit local variables

C #3.0 provides a new keyword var. With this keyword, the compiler will deduce the Data Type of the variable based on the initial value used to initialize the local variable.

Sample Code:

Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;

Namespace testvar
{
Class Program
{
Static void main (string [] ARGs)
{
// Define the int Array
Int [] intary = new int [] {1, 2, 3, 4, 5, 6 };

// Var varset = intary. Where (x => x> 3 );
// Execute the LINQ Query
VaR varset = from I in intary where I> 3 select I;

// Traverse the query results
Foreach (var v in varset)
{
Console. writeline (v );
}

// Output the varset type name and namespace
Console. writeline (varset. GetType (). Name );
Console. writeline (varset. GetType (). namespace );

Console. readkey ();
}
}
}

The running result is as follows:

Limitations on using implicit type variables:

1. The implicit type can only be used for declaring local variables in methods or attributes. var cannot be used to define the return value, parameter type, or type of data members.

2. The local variables declared using VAR must be assigned a value during the declaration, and cannot use null as the initial value.

Implicit local variables generate strongly typed data. In fact, the compiler will deduce a data type for the implicit type local variable during compilation, so the type of this variable has been determined in the final il code.

Why do we need implicit type variables?

The main purpose is to combine with the LINQ query technology. We can only use the VaR keyword when defining the data returned by the LINQ query.

Automatic attributes

Sample Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestVar
{
class AutoProperty
{
public string Name { get; private set; }

public AutoProperty() { }
}
}

In the preceding example, an attribute named name and of the string type is created for autoproperty using the automatic property syntax. The get method of this attribute is public, and the Set Method is private.

Extension Method

The extension method is used to extend a ready-made type without modifying the source code of the ready-made type.

Sample Code:

Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;

Namespace testvar
{
Public static class extend
{
// The first parameter is used to extend the string type.
Public static string replacea (this string STR, string deststr)
{
// Convert uppercase letter A to a specified string
Return Str. Replace ("A", deststr );
}
}
}

In the preceding example, the string type is extended to convert the uppercase letter A in the string to the specified string. Note that the extension method must be defined in a non-generic static class, and the extension method must also be static. You must import the namespace of the extension method.

Usage in the previous example: "aaaa". replacea ("B"); // convert uppercase letters A to B

In fact, after the extension method is compiled, in the Il code, the extension method call of the target type is only converted to direct call of the static extension method.

Division Method

C #3.0 expands the scope of the partial keyword. we can apply it to the method level. It allows us to build a method prototype in one file and implement it in another file. However, there are many restrictions:

1. The division method can only be defined in the Division class.

2. The division method must return the void type.

3. The out modifier is not allowed for the partial method parameters.

4. The partial method is always implicitly private. This limit is large, so the partial method is rarely used.

Example Syntax:

Definition: Partial void partialmethod (string Str );

Implementation: Partial void partialmethod (string Str ){......}

Object initializer

We can use the object initializer to simplify the object initialization syntax.

Example:

Class classa
{
Public int X {Get; set ;}
Public int y {Get; set ;}

Public classa (int x)
{
X = X;
}
}

Static void main (string [] ARGs)
{
// Initialize a common Class Object and assign a value to y using the object Initiator
Classa A = new classa (1) {Y = 2 };

// Set Initialization
List <point> points = new list <point>
{
New Point {x = 2, y = 2 },
New Point {x = 3, y = 3 },
};

Console. readkey ();
}

Anonymous type

Sometimes we may need to define classes to encapsulate some temporary data, but we do not need any associated methods, events and other custom functions. In this case, we can use the anonymous type.

All anonymous types automatically inherit system. Object. We can call the tostring, gethashcode, equals, and GetType methods on anonymous objects.

Sample Code:

Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;

Namespace testvar
{
Class Program
{
Static void main (string [] ARGs)
{
// Define two anonymous objects with the same attribute name and Value
VaR firstcar = new {color = "red", name = "BMW "};
VaR secondcar = new {color = "red", name = "BMW "};

// The object. Equals method compares whether two anonymous objects are equal
Console. writeline (firstcar. Equals (secondcar ));
// Use the = Operator to compare whether two anonymous objects are equal
Console. writeline (firstcar = secondcar );
// Compare whether two anonymous types are of the same type
Console. writeline (firstcar. GetType (). Name = secondcar. GetType (). Name );

Console. readkey ();
}
}
}

The code output is as follows:

In the preceding example, we can see that euqals is used to compare two objects of the anonymous type and returns true because the compiler overwrites the equals method of the anonymous type and compares the values of each data member of the anonymous type. However, when the = Operator is used for comparison, false is obtained. This is because the anonymous type does not have the overload = Operator, so the = Operator compares the references of two objects, instead of the content of two objects. Interestingly, true is returned for comparing the types of two anonymous objects. This means that when two anonymous types are declared at the same time (that is, the same attribute name and number), the compiler will only generate a definition of the same anonymous type for the two anonymous types.

Anonymous type restrictions:

1. The anonymous type does not support events, custom methods, custom operators, and custom rewriting.

2. The anonymous type is implicitly closed.

3. Only the default constructor is used to create an anonymous instance.

4. The anonymous type can also contain the anonymous type.

When to use the anonymous type: most of them are used for LINQ queries.

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.