New feature C #3.0 new syntax in vs08

Source: Internet
Author: User

C #3.0 new syntax

 

C #3.0 Overview
C #3.0 was officially released with vs2008 in early 2008.

C # Evolution
C #1.0 -- managed code
C #2.0 -- generic, anonymous method
C #3.0 -- LINQ, Lambda

C #3.0 Overview
C #3.0 new features include
Automatic attributes, inference type, Anonymous class, extension method, object initializing, set initializing, Lambda expression

-- Automatic attributes
Common class:
Class person
{
Private string firstname;
Private string lastname;
Private int age;

Public String firstname
{
Get {return firstname ;}
Set {firstname = value ;}
}
Public String lastname
{
Get {return lastname ;}
Set {lastname = value ;}
}
Public int age
{
Get {return age ;}
Set {age = value ;}
}
}
Classes with automatic attributes used:
Class personnew
{
Public String firstname {Get; set ;}
Public String lastname {Get; set ;}
Public int age {Get; set ;}
}
Demo: Automatic attributes

-- Automatic attribute nature
The compiler automatically generates these private variables for us using classes with automatic attributes.
After disassembly, the code is almost the same.

Summary of automatic attributes:
Typical scenarios of automatic attributes:
Only the basic value assignment function is included in the property code.
Simple entity class

When using automatic attributes, pay attention to the following points:
Automatic attributes cannot be read-only or write-only.
Because no private variables are declared, you can only reference them directly using the attribute name when using automatic attributes.

-- Object Initiator
Traditional Value assignment
//....
Person Lincoln = new person ();
Lincoln. firstname = "Lincoln ";
Lincoln. lastname = "Burrows ";
Lincoln. Age = 30;

Lincoln. sayhi ();
//....

Assign values using object Initiators
//....
Person Scofield = new person {
Firstname = "Michael ",
Lastname = "Scofield ",
Age = 20 };

Scofield. sayhi ();
//....
Demo: object initializer

-- Nested object initializer
// Nested object initializer
Person tbag = new person
{
Firstname = "Theodore ",
Lastname = "Bagwell ",
Age = 32,
Address = new address
{
Street = "Prison Sona ",
Country = "Panama"
}
};
The object initialization tool can not only contain simple value assignment code, but also contain other object initialization tools, namely, nested object initialization devices.

-- Summary of object initializer
Note the following code errors:
Person Scofield = new person
(
Firstname = "Michael ";
Lastname = "Scofield ";
Age = 22;
Address = new address
(
Street = "Prison Sona ";
Country = "Panama ";
)
);
The object is being initialized.
() Should be changed {}
; Should be changed,
Person Scofield = new person
{
Firstname = "Michael ",
Lastname = "Scofield ",
Age = 22,
Address = new address
{
Street = "Prison Sona ",
Country = "Panama ",
}
};

-- Set Initiator
The Set initializer allows us to initialize the set like an initialized array.
Traditional Value assignment
List <string> foxriver8 =
New List <string> ();
Foxriver8.add ("Michael ");
Foxriver8.add ("Lincoln ");
Foxriver8.add ("Sucre ");
Foxriver8.add ("Abruzzi ");
Foxriver8.add ("T-Bag ");
Foxriver8.add ("C-Note ");
Foxriver8.add ("tweener ");
Foxriver8.add ("Charles ");
Assign values by using the set Initiator
List <string> foxriver8 =
New List <string> {
"Michael ",
"Lincoln ",
"Sucre ",
"Abruzzi ",
"T-Bag ",
"C-Note ",
"Tweener ",
"Charles"
};
Demo: Set Initiator

Problem
Tom downloaded a graphics class library (only DLL, no source code) from the Internet, and it felt very useful. However, the rectangle class only has one area calculation method. Now, AI wants to add a method for calculating the perimeter for it. Let's take a look. What are the best solutions?
Extension Method

-- Simple extension method
Let's take a look at a simple example.
String greeting = "Welcome to Beijing ";
Greeting. sayhi ();
When does the string type have an additional sayhi () method? Demo: simple extension method

Code Analysis:
Define extension methods
// Using .....
Namespace helloorcas
{
Static class jbutility // static: the extension method must be defined in the static class.
{
// The extension method is a special static method;
// Add the keyword this before the first parameter;
// Here the string indicates that the extension method will be added for all string types
Public static void sayhi (this string S)

{
String message = string. Format (
"Hi, I am a string and my value is:/" {0 }/". ", S );
MessageBox. Show (message, "jbutility ",
Messageboxbuttons. okcancel,
Messageboxicon. information );
}
}
}

Pay attention to the static method and static class concepts. You can sum up the situations where this occurs, such as The indexer.

-- Define the syntax of the Extension Method
Syntax: Extension Method without parameters:
Static Method Name (this target type parameter name)
Syntax: Extension Method with parameters:
Static Method Name (this target type parameter name, parameter Type 1, parameter name 1 ,... .... )

-- Use of extension methods:
Note the following when using the extension method:
Define the required extension methods in a static class
If the extension method defined above is located in different namespaces, remember to reference it using the using statement.
When the class method and the extension method have the same name, the class method is preferred.

-- Example of Extension Method with parameters:
Define extension methods with Parameters
Public static void sayhi (this string S, string Caption)
{
String message = string. Format (
"Hi, I am a string and my value is:/" {0 }/". ", S );
MessageBox. Show (message, caption,
Messageboxbuttons. okcancel,
Messageboxicon. information );
}

Call an extension method with Parameters
String greeting = "Welcome to Beijing ";
Greeting. sayhi ("Beijing 2008 ");

Example: Extension Method with Parameters

On-site programming:
Compile the string class Extension Method to convert the string to Pascal
In case-sensitive format, run the following code:
String greeting = "Welcome to Beijing ";
Console. writeline (greeting. topascal ());
Output welcometobeijing

// Reference answer
Public static string topascal (this string S)
{
String [] words = S. Split (New char [] {''});
String result = string. empty;

Foreach (string word in words)
{
Result + = word. substring (0, 1). toupper () +
Word. substring (1). tolower ();
}
Return result;
}

-- Expansion method summary
Pay attention to the following points when using the extension method:
The extension method allows us to expand existing behaviors.
The extension method is a special static method.
Extension methods must be defined in static classes.
The extension method has a higher priority than the class method with the same name.
The extension method is only valid in a specified namespace.
Unless you must not abuse the Extension Method
(Use the extension method to be moderate.
Excessive use of extension methods may complicate the class structure and make the Behavior unpredictable.
In principle, if you can write the methods in the class code, do not make them extension methods)

-- Var keyword
VaR is a New Keyword introduced by C #3.0. It can automatically infer the local variable type based on the initial value.
Use the VaR Syntax:
VaR I = 2008;
VaR S = "ACCP ";
VaR d = 5.0;
VAR numbers = new int [] {1, 2, 3 };
VaR students = new dictionary <int, person> ();
Traditional methods:
Int I = 2008;
String S = "ACCP ";
Double D = 5.0;
Int [] numbers = new int [] {1, 2, 3 };
Dictionary <int, person> students =
New Dictionary <int, person> ();
The two have the same effect.
(In fact, The VaR keyword introduces a mechanism called "implicitly typed local variables ".
That is, "implied type local variable". Note that it clearly indicates that VaR modifies a local variable.
So although we sometimes refer to it as "inference type", it is actually not a "type" but "a local variable that can be inferred ")

-- Differences Between VaR and Object
Use VaR:
VaR name = "Beijing ";
Name = 2008;
Compilation error!
Cannot implicitly convert type 'int' to 'string'

Use object:
Object Name = "Beijing ";
Name = 2008;
You can compile'
Demo: differences between VaR and Object

-- Anonymous class
VaR P = new {
Name = "Tin ",
Age = 20,
Gender = "male "};
Console. writeline (P. Name); // although it is an anonymous type, it still supports smart sensing because it is strongly typed.
Demo: Anonymous class

-- Essence of anonymous classes
Automatically Generated Anonymous class name by the compiler

-- Var Summary
Check whether the following code is correct or not.
VaR X;
Error, must be initialized
Var y = {1, 2, 3 };
Error. Change to VaR x = new int [] {1, 2, 3 };
Int I;
VaR v = I ++;
Error. Variable I must be initialized first
VaR z = NULL;
Error. The initialization value cannot be null.

-- Var Summary
Note the following when using the keyword var:
Initialization must be completed at the same time when variables are defined.
You cannot use VaR to define a local variable initialized with a null value.
VaR itself is not a new type. In essence, it is only used to modify a local variable that can deduce the type.

-- Conclusion
Please state three or more new features of C #3.0.
What is the difference between using VAR and object to declare variables?
What are the advantages of introducing extension methods?

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.