It seems simple! Read the 7 most difficult mistakes that C # programmers make

Source: Internet
Author: User
Tags try catch

Programming mistakes are inevitable, even a small error can lead to expensive costs, smart people are good at learning from mistakes, try not to repeat the mistakes, in this article, I will focus on C # developers most likely to commit the 7 errors.

formatting strings

In C # Programming, string types are the easiest place to handle errors and often expensive, in the. NET framework, strings are immutable types, and when a string is modified, a new copy is always created, and the source string is not changed. Most developers always like to format a string 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, and here it uses multiple concatenation, thus creating three unnecessary string garbage copies in memory.

The best way is to use string. Format, because it uses variable StringBuilder internally and paves the way for purifying code.


String updatequerytext = String. Format ("UPDATE employeetable SET name= ' {0} '
WHERE empid={1} ", name, id);


• Nested exception handling

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


public class Nestedexceptionhandling
{
public void Mainmethod ()
{
Try
{
Some implementation
ChildMethod1 ();
}
catch (Exception Exception)
{
Handle exception
}
}

private void ChildMethod1 ()
{
Try
{
Some implementation
CHILDMETHOD2 ();
}
catch (Exception Exception)
{
Handle exception
Throw

}
}

private void ChildMethod2 ()
{
Try
{
Some implementation
}
catch (Exception Exception)
{
Handle exception
Throw
}
}
}


What happens to the code above if the same exception is processed more than once? There is no doubt that the performance overhead will soar.

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


public class Nestedexceptionhandling
{
public void Mainmethod ()
{
Try
{
Some implementation
ChildMethod1 ();
}
catch (Exception Exception)
{
Handle exception
}
}

private void ChildMethod1 ()
{
Some implementation
CHILDMETHOD2 ();
}

private void ChildMethod2 ()
{
Some implementation
}
}


• Using foreach on a large data set

Most developers prefer to use the Foreach loop, ignoring the For loop, because foreach is easier to use, but when working with large datasets, using foreach has proven to be expensive, and in the following code, I use both for and foreach to traverse the same database. The time consumed by the two cycle methods is shown in Figure 1.

 
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 for";
}
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 ();
}


1

Figure 1 Comparison of time consumed by the for and foreach loops traversing the same database
As you can see, the Foreach loop is noticeably slower, and it consumes almost twice times as much time as the for loop because of the DT in the Foreach Loop. Rows to access all rows in the database. It is therefore best to use a for loop when traversing large datasets.

Validating simple raw data types

Most developers do not know the built-in methods of validating raw data types, such as System.Int32, so many people do it themselves, and here is a code that implements its own validation of whether a string is a numeric 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, and a better approach is to use int as follows. TryParse:


int output = 0;
BOOL IsNumeric = Int. TryParse (value, out output);

According to my experience, int. TryParse is a faster, more concise approach.

Processing object Implementation IDisposable interface

In the. NET framework, the processing and use of objects is as important as the ideal way to implement the Dispose method of the IDisposable interface in a class, which can be processed by calling the Dispose method after the object of the class is used.

The following code shows the creation, use, and handling of a SqlConnection object:
[Code=c#]
public void Dalmethod ()
{
SqlConnection connection = null;
Try
{
Connection = new SqlConnection ("xxxxxxxxxx");
Connection. Open ();
Implement the data access
}
catch (Exception Exception)
{
Handle exception
}
Finally
{
Connection. Close ();
Connection. Dispose ();
}
}


In the above method, the connection processing is explicitly called in the last block of code, and if an exception occurs, the catch code block executes and then the last block of code is processed, so the connection remains in memory until the last block of code is executed. NET One of the basic principles of the framework is that resources should be freed when objects are not being used.

Here's a better way to call Dispose:


public void Dalmethod ()
{
using (SqlConnection connection = new SqlConnection ("Xxxxxxxxxx"))
{
Connection. Open ();
Implement the data access
}
}


When you use a using code block, the Dispose method on the object is invoked when the exit code block is executed, which guarantees that SqlConnection resources are processed and released as soon as possible, and you should also note that this applies to classes that implement the IDisposable interface.

Declaring public variables

It may sound a bit simple, but we often see a case of 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";
}
}


A accountnumber public variable is declared in the MyAccount class above, ideally accountnumber should be read-only, but the MyAccount class does not have any control over it.

The correct way to declare a public variable should be to use attributes such as:


public class MyAccount
{
private string _accountnumber;
public string AccountNumber
{
get {return _accountnumber;}
}

Public MyAccount ()
{
_accountnumber = "Xxxxxxxxxxxxx";
}
}


Here the MyAccount class has a good control over the AccountNumber public variables, it becomes read-only and cannot be modified by the caller class.

Access Data with System.Data.DataTable

I often see developers using column indexes to access data from a database, such as:


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, and the correct approach should be 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]);
}
}
}


Such code is more robust, the column order changes will not have any effect on the application, if you use local variables in one place to save the column name is better, even if your column name changes in the future, you do not have to modify the application code.

Summary

I want you to learn from the mistakes that you and other programmers make, to avoid making the same mistakes, and if you have a different view of the 7 types of mistakes that the C # programmers in this article are going to make, you are welcome to post your comments and ideas.

It seems simple! Read the 7 most difficult mistakes that C # programmers make

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.