Using C# Record Types for Immutable Data Models

Introduced in C# 9.0, record types offer a concise way to create immutable data models with value-based equality. They simplify many common programming tasks when working with data-centric classes.

What Are Record Types?

Records are reference types (like classes) but with built-in functionality for representing immutable data:

// Traditional class approach
public class PersonClass
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
    
    // Requires manual implementation of equality, hash code, etc.
}

// Equivalent record
public record Person(string FirstName, string LastName);

This simple declaration creates an immutable type with:

  • Constructor that accepts all properties
  • Public, init-only properties
  • Value-based equality (compares property values, not references)
  • ToString() implementation that displays all properties
  • Deconstruction support

Benefits of Using Records

1. Immutability by Default

Records are designed for immutability, making them perfect for:

  • Domain models
  • DTOs (Data Transfer Objects)
  • API responses
  • Configuration objects
var person = new Person("John", "Doe");
// person.FirstName = "Jane"; // Compile error - properties are init-only

2. Non-Destructive Mutation with 'with' Expressions

Need to change a property? Use the 'with' expression:

var person = new Person("John", "Doe");
var updatedPerson = person with { FirstName = "Jane" };

// person still refers to "John Doe"
// updatedPerson refers to "Jane Doe"

3. Value-Based Equality

Records automatically implement value equality:

var person1 = new Person("John", "Doe");
var person2 = new Person("John", "Doe");

Console.WriteLine(person1 == person2); // True
Console.WriteLine(person1.Equals(person2)); // True

4. Easy Class Hierarchies

Records can inherit from other records:

public record Person(string FirstName, string LastName);
public record Employee(string FirstName, string LastName, string Department) 
    : Person(FirstName, LastName);

When to Use Records

Use records when:

  • You need immutable objects
  • Equality should compare values, not references
  • You're creating simple data containers
  • You need non-destructive updates with the 'with' expression

Use traditional classes when:

  • You need mutable properties
  • You need reference-based equality
  • You need more control over property implementation

Performance Considerations

While records are convenient, be aware that:

  • The 'with' expression creates a new object (memory allocation)
  • Comparing large records can be slower than reference equality

Example: API Data Model

// API response model
public record WeatherForecast(
    DateTime Date,
    int TemperatureC,
    string Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

// Usage
var forecasts = await httpClient.GetFromJsonAsync<List<WeatherForecast>>("weatherforecast");

Records are a powerful addition to C#, making it easier to create robust data models with less boilerplate code.

0
51

Related

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!

3
274

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.

2
249

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
99