Menu

C# foreach vs for loop: Which is faster and when to use each

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;
    }
}
1
7

Related

Storing passwords as plain text is dangerous. Instead, you should hash them using a strong, slow hashing algorithm like BCrypt, which includes built-in salting and resistance to brute-force attacks.

Step 1: Install BCrypt NuGet Package

Before using BCrypt, install the BCrypt.Net-Next package:

dotnet add package BCrypt.Net-Next

or via NuGet Package Manager:

Install-Package BCrypt.Net-Next

Step 2: Hash a Password

Use BCrypt.HashPassword() to securely hash a password before storing it:

using BCrypt.Net;

string password = "mySecurePassword123";
string hashedPassword = BCrypt.HashPassword(password);

Console.WriteLine(hashedPassword); // Output: $2a$12$...

Step 3: Verify a Password

To check a user's login attempt, use BCrypt.Verify():

bool isMatch = BCrypt.Verify("mySecurePassword123", hashedPassword);
Console.WriteLine(isMatch); // Output: True

Ensuring proper hashing should be at the top of your list when it comes to building authentication systems.

0
19

String interpolation, introduced in C# 6.0, provides a more readable and concise way to format strings compared to traditional concatenation (+) or string.Format(). Instead of manually inserting variables or placeholders, you can use the $ symbol before a string to directly embed expressions inside brackets.

string name = "Walt";
string job = 'Software Engineer';

string message = $"Hello, my name is {name} and I am a {job}";
Console.WriteLine(message);

This would produce the final output of:

Hello, my name is Walt and I am a Software Engineer

String interpolation can also be chained together into a multiline string (@) for even cleaner more concise results:

string name = "Walt";
string html = $@"
    <div>
        <h1>Welcome, {name}!</h1>
    </div>";
11
29

Closing a SqlDataReader correctly prevents memory leaks, connection issues, and unclosed resources. Here’s the best way to do it.

Use 'using' to Auto-Close

Using using statements ensures SqlDataReader and SqlConnection are closed even if an exception occurs.

Example

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.

⚡ Alternative: Manually Close in finally Block

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.

0
7