- Community Pick
Introduction
Making mistakes is inevitable in programming. Even a small mistake could prove to be very costly. The wise thing is to learn from your mistakes and try not to repeat them. In this article I will be highlighting the mistakes which I consider to be the most common mistakes made by C# developers.
Note: These mistakes are not the worst, or most fatal mistakes, but they show up in a lot of C# code and
they should be avoided.
- 1
Use Format() for efficient string operations
The String datatype is always an immutable type in the .NET Framework. When a string is modified it always creates a new copy and never changes the original. Many developers use a VB- or Javascript-style technique like this to build up a string:
That code is really messy, and prone to typing errors. What's more, since the string is immutable, it creates three unnecessary garbage string copies in the memory as a result of multiple concatenations.
The better approach is to use string.Format() since it internally uses StringBuilder which is mutable:
It also paves the way for clean, easy-to-read code.
- 2
Avoid deeply-nesting exception handling
Developers who intend to write nested methods end up doing exception handling for each methods as shown in the below code:
So what would happen with the above code if the same exception were handled multiple times and moreover catching many exceptions? Throwing it will definitely add a performance overhead.
I try to avoid this by putting the exception handling in a single place; that is in the MainMethod as shown below:
- 3
Avoid using foreach on huge collections
Most developers prefer to use a foreach loop than a for loop because foreach is easier to use. This will however prove to be costly when working with collections with a large amount of data. Consider the below sample in which I am looping through the same DataTable using for and foreach.
And check out the timing data that shows in the following figure:
As you can see, the foreach loop is slow -- it takes almost double the amount of time as that of the for loop. This is because in the foreach loop dt.Rows will access all the rows in the datatable.
For bigger collections, always use a for loop in cases where looping is required.
- 4
Use TryParse() to validate primitive data types
Many developers are not aware of the built-in methods available for validating the primitive data types like System.Int32 and end up doing a custom implementation. The function below iis a typical custom implementation to validate whether the given string is numeric or not.
Since it involves try/catch, it is not the best way. A better approach would be to use int.TryParse as shown below:
This technique of using int.TryParse, in my opinion is definitely the faster and cleaner way.
- 5
Inefficient handling of objects implementing IDisposable
In the .NET Framework, disposing of an object is as important as consuming it. The ideal approach would be to implement the IDisposable interface's dispose method in the class, so after using the object of that class, it can be disposed by calling the dispose method.
Below is a sample where an SqlConnection object is created, used and disposed:
In the above method, the connection dispose is called explicitly in the finally block. In case there is an exception, then the catch block will be executed and after that the finally block will be executed to dispose the connection. So the connection is left in the memory until the finally block is executed. In the .NET Framework, one of the basic guidelines is to release the resource when it is not being used anymore.
Here is a better way of calling dispose:
When you have a using block as shown above, the dispose method on the object will be called as soon as the execution exits the block. That ensures that the SqlConnection resource is disposed and released at the earliest possilbe moment. You should also note that this will work on classes which implement the IDisposable interface.
- 6
Misuse of public member variables
This may sound simple, but it could really lead to the misuse of the public variables declared and could fetch unexpected usage of your class. Consider this example:
In the MyAccount class, a public variable AccountNumber is declared and assigned in the constructor. It is desired that the AccountNumber should be read-only and shouldn't be modified but when declared as shown, the MyAccount class doesn't have any control over it.
A better way to declare a public variable like AccountNumber is to use a property:
Here the MyAccount class has a good control over the AccountNumber. It is now read-only and cannot be changed by the caller.
- 7
Accessing a DataTable values using a hard-coded index
I frequently notice that most programmers access data from a DataTable using column indexes as shown below:
In the above scenario... What if the column order in the SQL query fetching data changes? Your application will break for sure! Always access the values through column names; one technique is:
The code above won't break, even if the database schema is altered and the column order is changed. Use a constant variable to hold the column names at a single place so that even if the column name changes in the future then you will have to modify the code in only one place.
Conclusion
I hope you can learn from mistakes myself and other programmers have made in the past. These are the seven most-common mistakes that I have seen -- I'm sure that you have seen others ones, too! Please feel free to utilize the comments section to showcase the conflicts and let me know what you think are other common issues as well.
by: PaulHews on 2010-09-19 at 21:26:40ID: 19622
System.Threading.Thread.Sl
instead of your looping code.
Once you actually reset your stopwatch you will probably find that foreach is actually a lot faster when looping through datatable rows. I did anyway, when I tried it with a watch.Reset(); in between the two loops.