Menu

Code-Bytes

Byte-sized articles, to get things done

Reading a file line by line is useful when handling large files without loading everything into memory at once.

✅ Best Practice: Use File.ReadLines() which is more memory efficient.

Example

foreach (string line in File.ReadLines("file.txt"))
{
    Console.WriteLine(line);
}

Why use ReadLines()?

Reads one line at a time, reducing overall memory usage. Ideal for large files (e.g., logs, CSVs).

Alternative: Use StreamReader (More Control)

For scenarios where you need custom processing while reading the contents of the file:

using (StreamReader reader = new StreamReader("file.txt"))
{
    string? line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

Why use StreamReader?

Lets you handle exceptions, encoding, and buffering. Supports custom processing (e.g., search for a keyword while reading).

When to Use ReadAllLines()? If you need all lines at once, use:

string[] lines = File.ReadAllLines("file.txt");

Caution: Loads the entire file into memory—avoid for large files!

2
177
3/28/2025

Measuring the execution time of C# methods is essential for performance optimization and identifying bottlenecks in your application.

The most straightforward approach uses the Stopwatch class from the System.Diagnostics namespace, which provides high-precision timing capabilities.

This approach is perfect for quick performance checks during development or when troubleshooting specific methods in production code.

Here's a practical example: Imagine you have a method that processes a large dataset and you want to measure its performance.

First, add using System.Diagnostics; to your imports. Then implement timing as shown below:

public void MeasurePerformance()
{
    Stopwatch stopwatch = new Stopwatch();
    
    // Start timing
    stopwatch.Start();
    
    // Call the method you want to measure
    ProcessLargeDataset();
    
    // Stop timing
    stopwatch.Stop();
    
    // Get the elapsed time
    Console.WriteLine($"Processing time: {stopwatch.ElapsedMilliseconds} ms");
    // Or use ElapsedTicks for higher precision
    Console.WriteLine($"Processing ticks: {stopwatch.ElapsedTicks}");
}

For more advanced scenarios, consider using the BenchmarkDotNet library, which offers comprehensive benchmarking with statistical analysis.

Simply install the NuGet package, decorate methods with the [Benchmark] attribute, and run BenchmarkRunner.Run<YourBenchmarkClass>() to generate detailed reports comparing different implementation strategies.

0
101
3/28/2025

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
71
3/28/2025

Working with dates is a common requirement in many applications, and calculating the difference between two dates is a particularly frequent task.

C# provides several powerful built-in methods to handle date arithmetic efficiently. Let's explore how to calculate date differences in C#.

Using DateTime and TimeSpan

The most straightforward way to calculate the difference between two dates in C# is by using the DateTime struct and the TimeSpan class:

DateTime startDate = new DateTime(2023, 1, 1);
DateTime endDate = new DateTime(2023, 12, 31);

TimeSpan difference = endDate - startDate;

Console.WriteLine($"Total days: {difference.TotalDays}");
Console.WriteLine($"Total hours: {difference.TotalHours}");
Console.WriteLine($"Total minutes: {difference.TotalMinutes}");
Console.WriteLine($"Total seconds: {difference.TotalSeconds}");

Getting Specific Units

Sometimes you need the difference in specific units (years, months, days). The TimeSpan class doesn't directly provide years and months, since these units vary in length. Here's how to handle this:

int years = endDate.Year - startDate.Year;
int months = endDate.Month - startDate.Month;

if (months < 0)
{
    years--;
    months += 12;
}

// Adjust for day differences
if (endDate.Day < startDate.Day)
{
    months--;
    int daysInMonth = DateTime.DaysInMonth(startDate.Year, startDate.Month);
    int dayDifference = daysInMonth - startDate.Day + endDate.Day;
    Console.WriteLine($"Years: {years}, Months: {months}, Days: {dayDifference}");
}
else
{
    int dayDifference = endDate.Day - startDate.Day;
    Console.WriteLine($"Years: {years}, Months: {months}, Days: {dayDifference}");
}

Using DateTimeOffset for Time Zone Awareness

If your application needs to handle dates across different time zones, consider using DateTimeOffset:

DateTimeOffset startDateOffset = new DateTimeOffset(2023, 1, 1, 0, 0, 0, TimeSpan.FromHours(-5));
DateTimeOffset endDateOffset = new DateTimeOffset(2023, 12, 31, 0, 0, 0, TimeSpan.FromHours(1));

TimeSpan timeDifference = endDateOffset - startDateOffset;
Console.WriteLine($"Total days including time zone difference: {timeDifference.TotalDays}");

Practical Applications

Date difference calculations are useful in many scenarios:

  • Calculating age from birth date
  • Determining duration between events
  • Computing business days between dates
  • Scheduling recurring events

With these techniques, you can handle most date arithmetic requirements in your C# applications efficiently and accurately.

0
112
3/28/2025

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
174
3/28/2025

The null coalescing assignment operator (??=) introduced in C# 8.0 provides a cleaner way to assign a value to a variable only when it's null. Let's see how and when to use it effectively.

Quick Example

// Instead of writing this:
if (myVariable == null)
    myVariable = defaultValue;

// You can write this:
myVariable ??= defaultValue;

Real-World Examples

Simple Property Initialization

public class UserSettings
{
    private List<string> _preferences;
    
    public List<string> Preferences
    {
        get
        {
            _preferences ??= new List<string>();
            return _preferences;
        }
    }
}

Service Caching

public class ServiceCache
{
    private ApiClient _client;
    
    public ApiClient GetClient()
    {
        _client ??= new ApiClient("https://api.example.com");
        return _client;
    }
}

Lazy Configuration Loading

public class ConfigurationManager
{
    private Dictionary<string, string> _settings;
    
    public string GetSetting(string key)
    {
        _settings ??= LoadSettingsFromFile();
        return _settings.TryGetValue(key, out var value) ? value : null;
    }
    
    private Dictionary<string, string> LoadSettingsFromFile()
    {
        // Load settings logic here
        return new Dictionary<string, string>();
    }
}

Common Gotchas

Reference vs Value Types

The operator works differently with value types - they need to be nullable:

// This won't compile
int count ??= 1;

// This works
int? count ??= 1;

Chaining Operations

// You can chain the operator
string result = first ??= second ??= "default";

// Equivalent to:
if (first == null)
{
    if (second == null)
    {
        second = "default";
    }
    first = second;
}
result = first;

Thread Safety

The operator is not thread-safe by default:

// Not thread-safe
public class SharedCache
{
    private static Dictionary<string, object> _cache;
    
    public object GetItem(string key)
    {
        // Multiple threads could evaluate null simultaneously
        _cache ??= new Dictionary<string, object>();
        return _cache.GetValueOrDefault(key);
    }
}

// Thread-safe version
public class SharedCache
{
    private static Dictionary<string, object> _cache;
    private static readonly object _lock = new object();
    
    public object GetItem(string key)
    {
        lock (_lock)
        {
            _cache ??= new Dictionary<string, object>();
            return _cache.GetValueOrDefault(key);
        }
    }
}

Performance Considerations

The null coalescing assignment operator is compiled to efficient IL code. It generally performs the same as an explicit null check:

// These compile to similar IL
obj ??= new object();

if (obj == null)
    obj = new object();

When to Use It

✅ Good use cases:

  • Lazy initialization of properties
  • Caching values
  • Setting default values for nullable types
  • Simplifying null checks in property getters

❌ Avoid using when:

  • You need thread-safe initialization (use Lazy<T> instead)
  • The right-hand expression has side effects
  • You need more complex null-checking logic

Visual Studio Tips

You can use Quick Actions (Ctrl+.) to convert between traditional null checks and the ??= operator. Look for the suggestion "Use null coalescing assignment" when you have a pattern like:

if (variable == null)
    variable = value;

Version Compatibility

This feature requires:

  • C# 8.0 or later
  • .NET Core 3.0+ or .NET Standard 2.1+
  • Visual Studio 2019+
0
47
3/28/2025

Slow initial load times can drive users away from your React application. One powerful technique to improve performance is lazy loading - loading components only when they're needed.

Let's explore how to implement this in React.

The Problem with Eager Loading

By default, React bundles all your components together, forcing users to download everything upfront. This makes navigation much quicker and more streamlined once this initial download is complete.

However, depending on the size of your application, it could also create a long initial load time.

import HeavyComponent from './HeavyComponent';
import AnotherHeavyComponent from './AnotherHeavyComponent';

function App() {
  return (
    <div>
      {/* These components load even if user never sees them */}
      <HeavyComponent />
      <AnotherHeavyComponent />
    </div>
  );
}

React.lazy() to the Rescue

React.lazy() lets you defer loading components until they're actually needed:

import React, { lazy, Suspense } from 'react';

// Components are now loaded only when rendered
const HeavyComponent = lazy(() => import('./HeavyComponent'));
const AnotherHeavyComponent = lazy(() => import('./AnotherHeavyComponent'));

function App() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <HeavyComponent />
        <AnotherHeavyComponent />
      </Suspense>
    </div>
  );
}

Route-Based Lazy Loading

Combine with React Router for even better performance:

import React, { lazy, Suspense } from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';

const Home = lazy(() => import('./pages/Home'));
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Settings = lazy(() => import('./pages/Settings'));

function App() {
  return (
    <BrowserRouter>
      <Suspense fallback={<div>Loading...</div>}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/dashboard" element={<Dashboard />} />
          <Route path="/settings" element={<Settings />} />
        </Routes>
      </Suspense>
    </BrowserRouter>
  );
}

Implement these techniques in your React application today and watch your load times improve dramatically!

0
72
3/28/2025

When working with large files, reading the entire file at once may be inefficient or unnecessary, especially when you only need the first few lines.

In C#, you can easily read just the first N lines of a file, improving performance and resource management.

Why Read Only the First N Lines?

Reading only the first few lines of a file can be beneficial for:

  • Quickly checking file contents or formats.
  • Processing large files without consuming excessive memory.
  • Displaying previews or samples of file content.

Reading the First N Lines with StreamReader

Here's a simple and efficient method using C#:

using System;
using System.IO;

class FileReader
{
    /// <summary>
    /// Reads the first N lines from a file.
    /// </summary>
    /// <param name="filePath">The path to the file.</param>
    /// <param name="numberOfLines">Number of lines to read.</param>
    /// <returns>Array of strings containing the lines read.</returns>
    public static string[] ReadFirstNLines(string filePath, int numberOfLines)
    {
        List<string> lines = new List<string>();

        using (StreamReader reader = new StreamReader(filePath))
        {
            string line;
            int counter = 0;

            // Read lines until the counter reaches numberOfLines or EOF
            while (counter < numberOfLines && (line = reader.ReadLine()) != null)
            {
                lines.Add(line);
                counter++;
            }
        }

        return lines.ToArray();
    }

Example Usage

Here's a practical example demonstrating the usage of the method above:

string filePath = "C:\\largefile.txt";
int linesToRead = 10;

string[] firstLines = FileReader.ReadFirstNLines(filePath, firstLinesCount);

foreach (string line in firstLines)
{
    Console.WriteLine(line);
}

Efficient and Shorter Alternative with LINQ

For a concise implementation, LINQ can also be used:

using System;
using System.IO;
using System.Linq;

class FileReader
{
    public static IEnumerable<string> ReadFirstNLines(string filePath, int numberOfLines)
    {
        // Take first N lines directly using LINQ
        return File.ReadLines(filePath).Take(numberOfLines);
    }
}

Usage Example with LINQ Method:

string path = "C:\\largeFile.txt";
int n = 10;

var lines = FileReader.ReadFirstNLines(path, n);

foreach (string line in lines)
{
    Console.WriteLine(line);
}

Best Practices

  • Use File.ReadLines instead of File.ReadAllLines for large files, as it does not load the entire file into memory.
  • Always handle exceptions properly to ensure your application remains stable.
  • For large files, avoid methods like ReadAllLines() which can negatively affect performance.

Final Thoughts

By limiting your reading operations to only the first few lines you actually need, you significantly enhance your application's efficiency and resource management.

0
36
3/28/2025

When working with SQL Server, you may often need to count the number of unique values in a specific column. This is useful for analyzing data, detecting duplicates, and understanding dataset distributions.

Using COUNT(DISTINCT column_name)

To count the number of unique values in a column, SQL Server provides the COUNT(DISTINCT column_name) function. Here’s a simple example:

SELECT COUNT(DISTINCT column_name) AS distinct_count
FROM table_name;

This query will return the number of unique values in column_name.

Counting Distinct Values Across Multiple Columns

If you need to count distinct combinations of multiple columns, you can use a subquery:

SELECT COUNT(*) AS distinct_count
FROM (SELECT DISTINCT column1, column2 FROM table_name) AS subquery;

This approach ensures that only unique pairs of column1 and column2 are counted.

Why Use COUNT DISTINCT?

  • Helps in identifying unique entries in a dataset.
  • Useful for reporting and analytics.
  • Efficient way to check for duplicates.

By leveraging COUNT(DISTINCT column_name), you can efficiently analyze your database and extract meaningful insights. Happy querying!

0
93
3/28/2025

Duplicate records in SQL Server can lead to inaccurate reporting, data inconsistencies, and performance issues. In this article, we’ll go over how to identify and safely remove duplicate rows while keeping at least one unique record.

Detecting Duplicates

To find duplicate records in a table, use the GROUP BY and HAVING clauses to count occurrences of each unique combination of values:

SELECT column1, column2, COUNT(*)
FROM YourTable
GROUP BY column1, column2
HAVING COUNT(*) > 1;

Replace column1, column2 with the columns that define a duplicate in your dataset.

If you need to see the actual duplicate rows, use a ROW_NUMBER() approach:

SELECT *
FROM (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY column1, column2 ORDER BY id) AS row_num
    FROM YourTable
) t
WHERE row_num > 1;

Here, id should be a unique column to order the duplicates.

Removing Duplicates

Method 1: Using ROW_NUMBER()

The safest way to remove duplicates while keeping one unique record is by using ROW_NUMBER().

WITH CTE AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY column1, column2 ORDER BY id) AS row_num
    FROM YourTable
)
DELETE FROM CTE WHERE row_num > 1;

This deletes all duplicate records while keeping the first occurrence.

Method 2: Using DISTINCT INTO a New Table

If you want to be extra cautious, create a new table with only unique records:

SELECT DISTINCT * INTO NewTable FROM YourTable;

Then, drop the old table and rename NewTable back to YourTable.

Final Thoughts

Always backup your data before running delete operations to prevent accidental data loss. By regularly cleaning up duplicates, you can keep your SQL Server database efficient and reliable.

0
18
3/28/2025