C# is an object-oriented, strongly-typed language used for web application development. The strict type checking of C#, help in finding most of the programming errors as early as possible. This can save a lot of time for C# programmers during programming, but, most of the programmers carelessly throw away the benefits of this checking, which leads to some of the issues discussed in this C# tutorial.
Jump to Section
1. Using a reference like a value or vice versa
If you don’t know whether the object you’re using is a value type or a reference type, you could run into some surprises. For example:
Point p1 = new Point(20, 30); Point p2 = p1; p2.X = 50; Console.WriteLine(p1.X); // 20 (does this surprise you?) Console.WriteLine(P2.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, both the Point and Pen objects were created the exact same way, but the value of p1 remained unchanged when a new x coordinate value was assigned to p2, whereas the value of pen1 was modified when a new color was assigned to pen2.
We can, therefore, deduce that p1 and p2 each contain their own copy of a Point object, whereas pen1 and pen2 contain references to the same Pen object.
2. Iterating through values instead of using LINQ
In almost any application, you’ll eventually need to enumerate values and store them in a List or a Collection. You could end up having to iterate through thousands of records.
For example, if you have 100,000 customers, iterating through each one of the records to find specific information using Foreach and for loop isn’t efficient. So, use LINQ (Language-Integrated Query). LINQ is specially designed to make it easier to query objects such as collections and lists.
foreach (Customer customer in CustomerList) { if (customer.State == "FL") { tax += customer.Balance; } }
Efficient Way
var customers = (from customer in CustomerList where customer.State == "FL" select customer.Balance).Sum();
3. Using “var” needlessly when you know the data type
Many developers use LINQ to retrieve a collection of values. Most of the time, you don’t know the output, and the “var” keyword helps you to avoid errors if a null or a data type that you weren’t expecting is returned.
However, if you know the data type, then define it.. so that other programmers can work with your code and maintain it without struggling to understand logic and output.
var customers = (from customer in CustomerList where customer.State == "FL" select customer.Balance).Sum();
4. Using public class variables instead of properties
A property is a member of the class that provides a flexible way to read, write, or compute the value of a private field. But, why we use properties when you can just make all of your class variables public?
One answer may be: You can control who can set a property with OOP properties, but you can’t with a public variable.
public decimal Total {get; protected set;}
In the above example, only the class itself or its derived classes have rights to set the total.
Consider an Order class that calculates a total for a customer’s order. You don’t want any external class to change the order, but you do want the Order class and any derived classes to add or subtract values stored by the Total variable. In case you tend to make the variable public, then any class can change an order total without any restrictions.
5. Not disposing of objects
Memory leaks are a real problem for any application. C# provides a Dispose method which you call after you’re finished with an object, so you don’t even need to remember to use it. The “using” statement will dispose objects and avoid the chances of memory leaks.
Inefficient file.Read(buffer, 0, 100);
In the above example, if you don’t dispose file object, you create a memory leak in the application to avoid this situation use using a statement.
Efficient using (FileStream file = File.OpenRead("numbers.txt")) { file.Read(buffer, 0, 100); }
Now the application reads a file and disposes of the object when it’s finished.
6. Using “” instead of String.Empty
String.Empty handles memory more efficiently than string x=””;
“” actually creates an object but String.Empty does not.
Also, it is a best practice to avoid hard coding like “”;
7. Using generic try-catch exceptions
Many programmers use the generic Exception class instead of specifying the actual exception that was thrown. All exception handling C# classes are derived from the general Exception class, and you can create custom exception classes that inherit the general class. However, you should always use specific exceptions.
Inefficient
try { newInteger = int.Parse(astring); } catch (Exception e) { // do something here }
Efficient
try { newInteger = int.Parse(astring); } catch (FormatException) { // do something here }
8. Wrapping entire methods in one try-catch block
A common mistake that most programmers do is to use one try-catch block for entire method. You should use try-catch blocks in the logic sections of your code. For example, don’t use the only one try-catch block when you have a method that reads a file, stores data in a variable, and then sends the data to a database. Add these three logics in separate blocks for efficient error handling.
9. Using string concatenation incorrectly
In older languages, it was common just to use the plus sign to concatenate the strings. This is that it’s an inefficient way to concatenate strings, so Microsoft introduced StringBuilder to help with memory and performance issues.
Use StringBuilder whenever you want to concatenate strings and manipulate them throughout your code. You don’t always need to use them for simple, basic strings, but it’s useful when you need to take a list of values such as those from a file and put them together to create one input that you then output to the user, or store to your database.
10. Forgetting to log errors
What happens when application users call you and say that the application is throwing an error during form submission? How do you know how this error occurs and what input the user is using? How do you know this error occur due to form submission or by some other event?
That’s what logs are for. You should always log errors. There are plenty of third-party tools that give you in-depth analysis, so it’s often easier to use a pre-existing application rather than build your own from the scratch.
Conclusion
I think every software programmer should have knowledge of all benefits provided by C#. I hope my article helps most programmers in handling the most common mistakes which they carelessly do. In case of any other queries, you can surely post your valuable comments in the comments section below…
- Business Intelligence Vs Data Analytics: What’s the Difference? - December 10, 2020
- Effective Ways Data Analytics Helps Improve Business Growth - July 28, 2020
- How the Automotive Industry is Benefitting From Web Scraping - July 23, 2020