The 10 most common mistakes that C # programmers make are http://www.oschina.net/translate/top-10-mistakes-that-c-sharp-programmers-make__.net

Source: Internet
Author: User
Tags exception handling
Source: Http://www.oschina.net/translate/top-10-mistakes-that-c-sharp-programmers-make about C #

C # is one of the few languages that reach the Microsoft Common Language Runtime (CLR). The language of the CLR can benefit from the features it brings, such as cross-language integration, exception handling, security enhancements, a simple model of component combinations, and debugging and Analysis Services. As a modern CLR language, C # is the most widely used, with its application scenarios for complex, professional development projects such as Windows desktops, mobile phones, and server environments.

C # is an object-oriented, strongly typed language. C # has strong type checking at compile and run time, so that most typical programming errors can be discovered as early as possible, and location positioning is fairly accurate. This can save programmers a lot of time, compared with those who are not rigidly wedded to a language that can be traced to inexplicable errors long after the violation has been done. However, many programmers have intentionally or unintentionally abandoned this detection somewhat, which leads to some of the issues discussed in this article.

about this article

This article describes the mistakes that 10 C # programmers often make, or traps they should avoid.

Although most of the errors discussed in this article are for C #, some errors are related to other languages that target the CLR, or to the language of the Framework Class Library (FCL).


Common errors #1: Use references as values, or vice versa

Programmers in C + + and many other languages are accustomed to assigning values to variables, either as a simple value or as a reference to an existing object. In C #, however, the value or reference is determined by the programmer who wrote the object, not by the programmer who instantiated the object and assigned the value. This often pits the novice programmer into C #.

If you do not know if the object you are using is a value type or a reference type, you may experience some surprises. For example,

  point point1 = new point (20, 30)";
  Point point2 = point1;   point2.
x = 50;   console.writeline (point1. X);       // 20  (does this surprise you?)    console.writeline (Point2. X);        // 50      pen pen1 = new
 pen (Color.Black);
  Pen pen2 = pen1;   pen2.
color = color.blue;   console.writeline (pen1. Color);     // blue  (or does this surprise you?)    console.writeline (Pen2. Color);      // blue 

As you can see, although point and pen objects are created the same way, when a new x's coordinate value is assigned to Point2, the  point1 value remains unchanged  . And when a new color value is assigned to the PEN2,PEN1, it changes as well. Therefore, we can infer that point1 and Point2 each contain a copy of their point object, while Pen1 and pen2 reference the same Pen object  . Without this test, how can we know the principle?

One way is to look at how the object is defined (in Visual Studio, you can place the cursor on the object's name and press the F12 key)

Public struct Point {...}        Defines a "value" type Public
class Pen {...} Defines a "reference" type

As shown above, in C #, the struct keyword is used to define a value type, and the class keyword is used to define a reference type. For those who have C + + programming backgrounds, it may be surprising to be confused by some similar keywords between C + + and C #.

If you want to rely on behavior that will vary by value type and reference type, for example, if you want to pass an object as an argument to a method and modify the state of the object in this method. You must make sure that you are dealing with the right type of object.

Common mistakes: misunderstanding. Default values for uninitialized variables

In C #, a worthy type cannot be empty. By definition, the type value of a value, even the value type of the initialization variable, must have a value. This is what is called the default value for this type. This usually causes the following, unexpected results, to check whether a variable is not initialized:

Class Program {
static point point1;      Static Pen Pen1;      static void Main (string[] args) {
Console.WriteLine (pen1 = = null);    True
Console.WriteLine (point1 = = null);      False (huh?)
}
}

Why not "point 1" empty. The answer is that the point is a value type, and, like the default value point (0,0), there is no null value. Fail to recognize that this is a very simple and common error in C #

Many (but not all) value types have a "IsEmpty" attribute, and you can see that it equals the default value:

Console.WriteLine (Point1.        IsEmpty); True

When you check whether a variable has been initialized, make sure you know that the value uninitialized is the type of the variable, and it will not be null by default.

The rice worm is blazing
Translated more than 1 years ago

0-person Top

The top translation is good Oh!

Common errors   #3: Comparing strings using inappropriate or unspecified methods

There are many ways to compare strings in C #.

Although many programmers use the = = operator to compare strings, this method is actually the least recommended. The main reason is that this method does not explicitly specify which type to use to compare strings in your code.

Instead, it is best to use the Equals method to determine whether strings are equal in C #:

  public bool equals (string value);   public  bool equals (string value, stringcomparison comparisontype); 
The

First Equals method (without comparisontype this parameter) is the same as the result of using the = = operator, but the advantage is that it explicitly indicates the comparison type. It compares strings by byte in order. In many cases, this is exactly the type of comparison you expect, especially when comparing some of the strings that are set programmatically, such as file names, environment variables, attributes, and so on. In these cases, it is only possible to compare the byte by order. The only bad thing about using the Equals method without the Comparisontype parameter is that people who read your code may not know what your comparison type is.

The

Use the Equals method with Comparisontype to compare strings, not only makes your code clearer, but also allows you to think about what type of string to compare. This method is well worth using, because although there is not much difference between a sequential comparison and a language-by-region comparison, there may be significant differences in other languages. If you ignore this possibility, it is undoubtedly for yourself in the future of the road to dig a lot of "pits." For example:

  string s =  "Strasse";      // outputs false:   console.writeline (s ==  "stra&
Szlig;e ");
  console.writeline (S.equals ("straße"));
  console.writeline (S.equals ("Straße",  stringcomparison.ordinal));   console.writeline (S.equals ("Straße",  stringcomparison.currentculture));            console.writeline (s.equals ("Straße", 
StringComparison.OrdinalIgnoreCase));      // outputs true:   console.writeline (s.equals ("Straße"),
 stringcomparison.currentculture));   console.writeline (S.equals ("Straße",  stringcomparison.currentcultureignorecase));
The safest practice for

is to always provide a comparisontype argument for the Equals method. The following are some of the basic guidelines for

:

Use localized comparisons when comparing user-entered strings or displaying string comparison results to users (currentculture  or Currentcultureignorecase )。

When comparing strings used for programming, use the original comparison (ordinal  or  ordinalignorecase)

InvariantCulture and invariantcultureignorecase are generally not used unless they are in restricted situations because the original comparisons are usually more efficient. If comparisons with local culture are essential, it should be carried out as a comparison based on the current culture or another special culture.

In addition, for the equals  method, strings also typically provide a compare method that provides relative order information for strings rather than testing for equality. This method can be applied well to the <, <=, > and >=  operators, and is also applicable to the above discussion.

Common pitfalls #4: to manipulate a set using an iterative (rather than declarative) statement

In C # 3.0, the introduction of LINQ changed our previous query and modification of collection objects Operation. Since then, you should use LINQ to manipulate the collection instead of iterating through it.

Some C # programmers are not even aware of the existence of LINQ, but the people who do not know are gradually decreasing. But others mistakenly think that LINQ is used only in database queries, because LINQ keywords and SQL statements are so much alike.

Although the query operation of a database is a very typical application of LINQ, it can also be applied to various enumerable collection objects. (for example, any object that implements the IEnumerable interface). For example, if you have an array of account types, do not write the following:

  decimal total = 0;  foreach " (account  account in myaccounts)  {    if  (account. status ==  "active")  {      total += account.
Balance; &NBSP;&NBSP;&NBSP;&NBSP}   } 

You just write:

  decimal total = " (from account in  Myaccounts                where  account. status ==  "Active"                  Select account. Balance). Sum (); 

Although this is a very simple example, in some cases a single LINQ statement can easily replace dozens of statements in an iterative loop (or nested loop) in your code. Less code often means that the chances of producing bugs are less likely to be introduced. However, remember that there may be a trade-off in performance. In scenarios where performance is critical, especially if your iteration code can make assumptions about your collection, LINQ does not, so be sure to compare performance between the two methods.

Zhao-Blue sky
Translation 1 years ago

0 people top

Top   translation Good Oh!

#5常见错误: The underlying object

is not considered in the LINQ statement for processing the abstract manipulation Collection task, and LINQ is undoubtedly huge. Whether they are objects in memory, database tables, or XML documents. In such a perfect world, you don't need to know the underlying object. The mistake here, however, is to assume that we live in a perfect world. In fact, the same LINQ statement can return different results when executed on the exact same data, if the data happens to be in a different format.

For example, consider the following statement:?

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.