C # seemingly simple explanation of seven major errors

Source: Internet
Author: User
Tags try catch

Making mistakes in programming is inevitable. Even a small mistake may lead to expensive costs. smart people are good at learning from mistakes and try to avoid making mistakes again. In this article, we will focus on the seven mistakes C # developers are most likely to make.

 • Format strings

In C # programming, the string type is the easiest place to handle errors, and the cost is often very expensive. in the. NET Framework, a string is an unchangeable type. When a string is modified, a new copy is always created without changing the source string, most developers always like to format strings using the following method:

String updatequerytext = "Update employeetable set name = '" + name + "'where empid =" + ID;

 
The above code is too messy. Because the string is immutable, multiple concatenation is used here, so three unnecessary spam copies of the string will be created in the memory.

The best way is to use string. format, because it uses variable stringbuilder internally and paves the way for code cleansing.

String updatequerytext = string. Format ("Update employeetable set name = '{0}' Where empid = {1}", name, ID );

 
 • Nested Exception Handling

Developers like to add nested methods for exception handling at the end of the method, such:

Public class nestedexceptionhandling
{
Public void mainmethod ()
{
Try
{
// Some implementation
Childmethod1 ();
}
Catch (exception)
{
// Handle exception
}
}

Private void childmethod1 ()
{
Try
{
// Some implementation
Childmethod2 ();
}
Catch (exception)
{
// Handle exception
Throw;

}
}

Private void childmethod2 ()
{
Try
{
// Some implementation
}
Catch (exception)
{
// Handle exception
Throw;
}
}
}

 

If the same exception is processed multiple times, what will happen to the above Code? Without a doubt, performance overhead will increase dramatically.

The solution is to separate the exception handling methods, such:

Public class nestedexceptionhandling
{
Public void mainmethod ()
{
Try
{
// Some implementation
Childmethod1 ();
}
Catch (exception)
{
// Handle exception
}
}

Private void childmethod1 ()
{
// Some implementation
Childmethod2 ();
}

Private void childmethod2 ()
{
// Some implementation
}
}

• Use foreach on large datasets

Most developers prefer to use a foreach loop instead of a for loop, because foreach is easier to use, but when operating a large data set, using foreach has proved to be expensive, in the following code, I use both for and foreach to traverse the same database. Figure 1 shows the time consumed by the two loop methods.

Static void main (string [] ARGs)
{
Datatable dt = populatedata ();
Stopwatch watch = new stopwatch ();

// For Loop
Watch. Start ();
For (int count = 0; count <DT. Rows. Count; count ++)
{
DT. Rows [count] ["name"] = "modified in ";
}
Watch. Stop ();
Console. writeline ("time taken in for loop: {0}", watch. elapsed. totalseconds );

// Foreach Loop
Watch. Start ();
Foreach (datarow row in DT. Rows)
{
Row ["name"] = "modified in foreach ";
}
Watch. Stop ();
Console. writeline ("time taken in for each loop: {0}", watch. elapsed. totalseconds );

Console. readkey ();
}

Figure 1 Comparison of time consumed by for and foreach loop traversal of the same database

 
It can be seen that the foreach loop is obviously slower, and it consumes almost twice the time of the For Loop, because DT. rows in the foreach loop needs to access all rows in the database. Therefore, we recommend that you use the for loop when traversing large data sets.

 • Verify simple raw data types

Most developers do not know the built-in methods for verifying the original data type, such as system. int32, so many people implement it by themselves. Below is a self-implemented code to verify whether a string is a numerical value:

Public bool checkifnumeric (string value)
{
Bool isnumeric = true;
Try
{
Int I = convert. toint32 (value );
}
Catch (formatexception exception)
{
Isnumeric = false;
}
Return isnumeric ;}

 

It uses a try catch statement, so it is not the best practice. A better way is to use Int. tryparse as follows:

Int output = 0;
Bool isnumeric = int. tryparse (value, out output );

 
In my experience, Int. tryparse is a faster and more concise method.

• Implement the idisposable interface for processing objects

In. in the. NET Framework, object processing and usage are equally important. The ideal solution is to implement the dispose method of the idisposable interface in the class. After using the object of this class, you can call the dispose method for processing.

The following code shows how to create, use, and process a sqlconnection object:

Public void dalmethod ()
{
Sqlconnection connection = NULL;
Try
{
Connection = new sqlconnection ("xxxxxxxxxx ");
Connection. open ();
// Implement the data access
}
Catch (exception)
{
// Handle exception
}
Finally
{
Connection. Close ();
Connection. Dispose ();
}
}

 

In the above method, connection processing is explicitly called in the last code block. If an exception occurs, the catch code block will be executed, and then the last code block will be executed to process the connection, therefore, the connection will remain in the memory until the last code block is executed ,. A basic principle of Net Framework is to release resources when objects are not used.

The following is a better way to call dispose:

Public void dalmethod ()
{
Using (sqlconnection connection = new sqlconnection ("xxxxxxxxxx "))
{
Connection. open ();
// Implement the data access
}
}

 

When you use the using code block, the dispose method on the object will be called when you exit the code block. This ensures that the sqlconnection resources are processed and released as soon as possible, you should also note that this method also applies to classes that implement the idisposable interface.

 • Declare Public Variables

It may sound a bit simple, but we often see misuse of public variable declarations. Let's look at an example:

Static void main (string [] ARGs)
{

Myaccount account = new myaccount ();
// The caller is able to set the value which is unexpected
Account. accountnumber = "yyyyyyyyyyyyyy ";

Console. readkey ();
}

Public class myaccount
{
Public String accountnumber;

Public myaccount ()
{
Accountnumber = "xxxxxxxxxxxxx ";
}
}

 

In the above myaccount class, a public variable of accountnumber is declared. Ideally, accountnumber should be read-only, but the myaccount class has no control over it.

The correct way to declare public variables is to use attributes, such:

Public class myaccount
{
Private string _ accountnumber;
Public String accountnumber
{
Get {return _ accountnumber ;}
}

Public myaccount ()
{
_ Accountnumber = "xxxxxxxxxxxxx ";
}
}

 

Here, the myaccount class implements good control over the public variables of accountnumber. It becomes read-only and cannot be modified by the caller class.

• Use System. Data. datatable to access data

I often see that developers use column indexes to access data from databases, such:

Public class myclass
{
Public void mymethod ()
{

// Getdata fetches data from the database using a SQL query
Datatable dt = dataaccess. getdata ();
Foreach (datarow row in DT. Rows)
{
// Accessing data through column Index
Int empid = convert. toint32 (row [0]);
}
}
}

 

In this way, if the column order changes when the SQL query matches the data, your application will be affected. The correct way is to use the column name to access the data.

Public class myclass
{
Private const string col_emp_id = "empid ";
Public void mymethod ()
{

// Getdata fetches data from the database using a SQL query
Datatable dt = dataaccess. getdata ();
Foreach (datarow row in DT. Rows)
{
// Accessing data through column name
Int empid = convert. toint32 (row [col_emp_id]);
}
}
}

 

This code is more stable, and changing the column order will not affect the application. If you use local variables to save the column name in one place, even if your column name changes in the future, you do not need to modify the application code.

  Summary

I hope that you can learn from the mistakes made by yourself and other programmers to avoid making the same mistakes, if you have different opinions on the 7 errors that C # programmers often make in this article, you are welcome to express your comments and ideas.

 

From: http://tech.it168.com/a2010/0927/1108/000001108666.shtml

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.