When it comes to iterating over collections in C#, the performance difference between foreach and for loops primarily depends on the collection type being traversed.
For arrays and Lists, a traditional for loop with indexing can be marginally faster because it avoids the overhead of creating an enumerator object, especially in performance-critical scenarios.
The foreach loop internally creates an IEnumerator, which adds a small memory allocation and method call overhead.
However, for most modern applications, this performance difference is negligible and often optimized away by the JIT compiler.
The readability benefits of foreach typically outweigh the minor performance gains of for loops in non-critical code paths.
Collections like LinkedList or those implementing only IEnumerable actually perform better with foreach since they don't support efficient random access.
The rule of thumb: use foreach for readability in most cases, and only switch to for loops when benchmarking shows a meaningful performance improvement in your specific high-performance scenarios.
Example
// Collection to iterate List<int> numbers = Enumerable.Range(1, 10000).ToList(); // Using for loop public void ForLoopExample(List<int> items) { int sum = 0; for (int i = 0; i < items.Count; i++) { sum += items[i]; } // For loop can be slightly faster for List<T> and arrays // because it avoids creating an enumerator } // Using foreach loop public void ForEachLoopExample(List<int> items) { int sum = 0; foreach (int item in items) { sum += item; } // More readable and works well for any collection type // Preferred for most scenarios where performance isn't critical } // For a LinkedList, foreach is typically faster public void LinkedListExample(LinkedList<int> linkedItems) { int sum = 0; // This would be inefficient with a for loop since LinkedList // doesn't support efficient indexing foreach (int item in linkedItems) { sum += item; } }
When working with URLs in C#, encoding is essential to ensure that special characters (like spaces, ?, &, and =) don’t break the URL structure. The recommended way to encode a string for a URL is by using Uri.EscapeDataString(), which converts unsafe characters into their percent-encoded equivalents.
string rawText = "hello world!"; string encodedText = Uri.EscapeDataString(rawText); Console.WriteLine(encodedText); // Output: hello%20world%21
This method encodes spaces as %20, making it ideal for query parameters.
For ASP.NET applications, you can also use HttpUtility.UrlEncode() (from System.Web), which encodes spaces as +:
using System.Web; string encodedText = HttpUtility.UrlEncode("hello world!"); Console.WriteLine(encodedText); // Output: hello+world%21
For .NET Core and later, Uri.EscapeDataString() is the preferred choice.
Closing a SqlDataReader correctly prevents memory leaks, connection issues, and unclosed resources. Here’s the best way to do it.
Using using statements ensures SqlDataReader and SqlConnection are closed even if an exception occurs.
using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users", conn)) using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { Console.WriteLine(reader["Username"]); } } // ✅ Auto-closes reader here } // ✅ Auto-closes connection here
This approach auto-closes resources when done and it is cleaner and less error-prone than manual closing.
If you need explicit control, you can manually close it inside a finally block.
SqlDataReader? reader = null; try { using SqlConnection conn = new SqlConnection(connectionString); conn.Open(); using SqlCommand cmd = new SqlCommand("SELECT * FROM Users", conn); reader = cmd.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader["Username"]); } } finally { reader?.Close(); // ✅ Closes reader if it was opened }
This is slightly more error prone if you forget to add a finally block. But might make sense when you need to handle the reader separately from the command or connection.
In C#, you can format an integer with commas (thousands separator) using ToString with a format specifier.
int number = 1234567; string formattedNumber = number.ToString("N0"); // "1,234,567" Console.WriteLine(formattedNumber);
Explanation:
"N0": The "N" format specifier stands for Number, and "0" means no decimal places. The output depends on the culture settings, so in regions where , is the decimal separator, you might get 1.234.567.
Alternative:
You can also specify culture explicitly if you need a specific format:
using System.Globalization; int number = 1234567; string formattedNumber = number.ToString("N0", CultureInfo.InvariantCulture); Console.WriteLine(formattedNumber); // "1,234,567"
Register for my free weekly newsletter.