C #2.0 improvement on the existing syntax

Source: Internet
Author: User

[Self-ordering]

Although Microsoft Visual Studio. NET 2005 (it used to be called Visual Studio. net 2004) has been postponed its release date, but the developers' guesses about it and the media's "Exposure" on all aspects of it also seem to be full of the Internet. However, articles related to C # Seem to have two aspects:. NET 2005 IDE features, introduce the four major features (generic, anonymous method, iterator, and incomplete type) introduced in C #2.0 )". I don't want to talk about ide research. Microsoft is Microsoft, and his window applications never have to be mentioned. As far as the language itself is improved, after I have finished my speech at Microsoft Professional Developers Conference 2003 (2003.10, Los Angeles, CA) by Anders hejlsberg, I found that in addition to these four features, there are also some little-known features that are not even mentioned in the official Microsoft documentation C # Language Specification Version 2.0. These features improve the logic of the language. So I wrote a lot of practical programs to study these features, and finally made a cost document. This is intended to be published in the magazine "csdn development experts", but the level of helplessness is limited, and it can only be left in this corner. I hope to be helpful to those who are interested in the C # language.

-- Lover_p: Room 221, building 1, Beijing Institute of Technology

[Body]

Microsoft has added many exciting new features to its forthcoming C #2.0 (Visual C # Whidbey. In addition to major improvements such as generic, iterator, anonmynous, and partial type, the existing syntax has been greatly improved, greatly facilitating. net Framework Program Design, and further enhance the unique high logic of C # language. In this article, I will introduce these improvements. (C # in this Article refers to C #1.2 and earlier versions, while C #2.0 refers to the C # Whidbey that has not been officially launched by Microsoft; all the code in this article is tested under the C # compiler with version 8.00.30703.4. The error message marked with * must be a C # compiler with a version of 7.10.3052.4 .)

Static class

People who use C # For. NET Framework programming should know that a class cannot be declared as static. For example, the following class declaration:

Public static Class {
Static int I;
}

It is invalid in C #. When we try to compile this code, we will get the following compilation Error *:

Error cs0106: the modifier "static" is invalid for this item

Because we cannot use the static modifier to modify a class, we can always declare both static members and instance members in the class. This will undoubtedly bring great flexibility. However, if we want a class to be static, that is, we want to force all the members of this class to be static, we can't do anything about it, the only thing you can do is to declare all the members as static. When we forget to use the static modifier for a static member (although this is a "low-level error", it may still happen), unexpected errors will occur. Most importantly, for a logical static class (all members use the static modifier to declare the class ), we can even declare a variable of this class and use the new operator to generate an instance of this class! This is clearly not what we expected.

In C #2.0, the concept of static classes is provided, allowing static modifiers to modify classes, and the above Code can be compiled. If a class declaration contains a static modifier, all the members of the class will be forcibly declared as static. In this case, if we intentionally declare an instance Member in the class or accidentally forget the static modifier in the member declaration, as shown in the following code:

Public static Class {
Int I;
}

The compiler reports an error:

Error cs0708: 'A. I ': cannot declare instance members in a static class

At the same time, if we declare the variables of this class or try to create an instance of this class, the following code:

Public class test {
A A; // error cs0723
Void Foo (){
A = new A (); // error cs0712
}
}

The following two compilation errors are returned:

Error cs0723: cannot declare variable of static type 'A'
Error cs0712: cannot create an instance of the static class 'A'

Obviously, the support for static classes in C #2.0 greatly avoids unexpected mistakes in writing programs, especially enhances the logic of static classes and improves the readability of code.

Restricted accessibility of attributes

C # provides us with a very convenient attribute definition, so that we can get the same security as accessing functions as if we were a member of the primary class's public variable. However, C # only allows attribute setting actions (set {...}) and get action (get {...}) has the same accessibility (specified by the public, internal, and private modifiers of the attribute Declaration ). So, when we want to allow classes in any assembly to obtain the attributes of a class, but only allow the Assembly where the class is located or the private members of the class to set this attribute, we can only declare this attribute as public and read-only (that is, use the public modifier to declare it, but only get {} domain ), internal or private members can only set attributes by setting the values of internal or private variable members related to this attribute:

Public Class {
Int _ intvalue; // an int-type member variable associated with the attribute

// Public and read-only attribute, allowing any class to obtain the value of this attribute:
Public int value {
Get {return _ intvalue ;}
}

// The following method needs to set the above attributes,
// But it can only be done by accessing private member variables,
// Handle other errors
Private void somemethod (){
Int I;
//......
// The following if-else statement is only used to set the attribute value:
If (0 <I & I <10 ){
_ Intvalue = I;
}
Else {
// Handle errors
}
}
}

Obviously, this approach is very troublesome. If the value of the member variable is changed in multiple places, the Code may become lengthy and unreadable, and errors may occur. For example, this class has another method:

Private void anothermethod (){
Int I;
//......
// The following if-else statement is only used to set the attribute value,
// However, an error occurred while detecting the I interval.
If (0 <I & I <= 10 ){
_ Intvalue = I;
}
// No error handling
//......
}

The above method has an error in the check interval of the value that will be assigned to the private variable member. This error is very likely to happen. Once this method is called, _ intvalue may have a wrong value, and an external Assembly accessing the value attribute may have a logical error. It is quite difficult to solve such errors. Moreover, if other members in a group are responsible for designing other classes in the same assembly, it is inhuman to require them to write so much code in the method and perform error checks.

Of course, we may think of putting this job of setting attribute values into an internal method for integration:

// The Private member of the class or class in the Assembly passes
// The following internal method is used to set the above attributes.
Internal void _ setintvalue (INT newvalue ){
If (0 <newvalue & newvalue <10 ){
_ Intvalue = newvalue;
}
Else {
Throw new system. invalidargumentexception (
"The new value must greater than 0 and less than 10"
);
}
}

// The following method needs to set the above attributes
Private void somemethod (){
Int I;
//......
_ Setintvalue (I); // call the internal method
}

Although this avoids the appearance of logical errors (at least makes it easier to solve the problem when an error occurs), it is still not readable, especially the logic is poor, it is far from the meaning of "attribute.

However, C #2.0 allows us to set the accessibility for the get {} and set {} domains of the properties respectively. We can simply write the above Code:

Public Class {
Int _ intvalue; // an int-type member variable associated with the attribute

// Public attributes,
// Allows any class to obtain the value of this attribute,
// But only the classes in the Assembly and Private Members in the class
// Set attribute values
Public int value {
Get {
Return _ intvalue;
}
Internal set {
If (0 <Value & value <10 ){
_ Intvalue = value;
}
Else {
Throw new system. invalidargumentexception (
"The new value must greater than 0 and less than 10"
);
}
}
} // Property

// The following method needs to set the above attributes
Private void somemethod (){
Int I;
//......
Value = I;
}
}

It is especially convenient to access this attribute among other class members in the Assembly:

// This is another class in the same assembly:
Public Class B {
Public A somemethod (){
A A = new ();
A. value = 8; // set the attribute here for convenience!
Return;
}
}

It can be seen that the ability to set accessible limits for the acquisition and setting of properties greatly enhances the readability and Language Logic of the C # program, and the written program has stronger maintainability.

Namespace alias

In C #, when using a class (such as declaring a member variable or calling a static method), you must specify the full name of the class, that is, the namespace prefix and the class name. If we want to print "Hello, world!" on the console !", You need to write:

System. Console. writeline ("Hello, world !");

Here, system is the namespace, console is the class name, And writeline () is the method we want to call.

Such a requirement will obviously cause code to become abnormal and redundant. Therefore, C # provides us with the Using Keyword (command ). By using the using command, we can specify a series of namespaces to the compiler. When the class name appears in the program, the compiler will automatically search for the class in these namespaces. Therefore, the above Code can be written:

Using system;
//......
Public class test {
Public static void main (){
Console. writeline ("Hello, world !");
}
}

Isn't that the classic "Hello World" example? Obviously, this writing method is much more convenient and can greatly improve the development efficiency.

However, the two namespaces may have classes with the same name, and we just need to use these classes with the same name. This situation often occurs. For example, there are three timer classes in the. NET Framework Class Library: system. Timer. Timer, system. Threading. timer, and system. Windows. Forms. Timer. We may need two timer classes: one system. timer. timer is used to check the application or system status at a fixed interval in the background. windows. forms. timer is used to display simple animations on the user interface. At this time, even if we use the using command, we still need to add the namespace when these classes appear:

Using system. timer;
Using system. Windows. forms;
//......
Public class mainform: FORM {
System. Timer. Timer checktimer;
System. Windows. Forms. Timer animatetimer;
//......
}

Such a program is still lengthy.

In C #2.0, the use of the using command is extended. We can use the using command to specify an alias for the namespace. When we need to reference this namespace, we can simply use its alias. However, aliases are identical to namespaces. When referencing a namespace type, you only need to add a dot ". and then follow the type name. When referencing the type in the namespace represented by an alias, the statement is the same. The above example can be written as follows:

Using timer usage = system. timer;
Using winform = system. Windows. forms;
//......
Public class mainform: winform. FORM {
Using timer. Timer checktimer; // use the same namespace
Winform. Timer animatetimer;
//......
}

We can see that such code is much simpler.

Compiler instructions

When we debug the C # program, we often declare some temporary variables to monitor the program status and delete these declarations after the debugging is complete. However, when we declare such a temporary variable, but it is not used during the debugging process, we usually get a lot of such:

Warning cs0168: The variable 'exp 'is declared but never used

Warning. However, we know that such warnings are harmless. Similarly, many other times we get some warning, but we have to find the error messages we need from a large number of harmless warnings.

C #2.0 provides us with a new compiler command: Pragma warning, which allows us to block some warnings that we confirm harmless in a piece of code (by specifying a warning number ). Previously, this kind of work could only be done by a specific compiler (such as the/nowarn option of the C # compiler) or the corresponding ide options. For example, we can use the following code to prevent the above warning of "unused Parameters:

Public class test {
Public void somemethod (){
// The following compiler command disables the warning of "unused Parameters:
# Pragma warning disable 0168
Int tempstatus;
//......
// The following compiler commands allow the generation of "unused Parameters" warning again:
# Pragma warning restore 0168
}
}

In this way, when the compiler compiles the somemethod () method, the above "unused Parameters" warning will not be generated, but this warning will still be generated when compiling other code segments, because we re-opened the warning using the # pragma warning restore command.

Fixed buffer size

Finally, in addition to some of the above features, C #2.0 also provides a new feature of "fixed size buffers. That is to say, you can declare a fixed-size array in the structure as in the C language, which is achieved through the system. runtime. compilerservices. fixedbufferattribute attribute and fixed keyword (refer to the reference 26th page ):

[System. runtime. compilerservices. fexedbuffer]
Public struct buffer {
Public fixed char buffer [128];
}

However, since my compiler does not yet support this feature, I will not introduce it here.

 

The above is a brief introduction to some of the improvements made to the existing features in C #2.0 in addition to major improvements such as generics, iterators, anonymous methods, and segment types. These improvements seem tiny, but greatly enhance the logic of the C # language, so that we can write code that is more beautiful and more maintainable. My introduction is very simple and may even be incorrect. I hope you will give me some advice. (Contact: lyb_dotNET@hotmail.com)

References

[1] Visual C # Whidbey: Language ehancements, Anders hejlsberg's presentation at Microsoft Professional Developers Conference 2003 (2003.10, Los Angeles, CA) and its PowerPoint documents.

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.