Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Fix Code Holding a Reference to an Array Element Silently Pointing at the Old Array After Array.Resize Allocates a New One

- 01.11.26 - ErcanOPAK

🔧 Fix Code Holding a Reference to an Array Element Silently Pointing at the Old Array After Array.Resize Allocates a New One

Array.Resize looks, from its name, like it grows or shrinks the array in place, but a C# array’s length is fixed at the moment it’s created and can never actually change – what Array.Resize really does is allocate an entirely new array of the requested size, copy over as many elements as fit, and reassign the ref parameter so the variable passed to it now points at that new array instead of the old one. Any other variable, field, or captured closure that was holding a reference to the original array object, rather than to the ref parameter Array.Resize was given, keeps pointing at that original, now-orphaned array exactly as it was before the resize – it doesn’t see the new elements Array.Resize added, and if the resize shrank the array, it still sees the elements that were supposedly removed, because as far as that other reference is concerned, nothing happened to the array it’s holding at all.

🔎 The Problem

public class Buffer
{
    public int[] Data = new int[] { 1, 2, 3 };
}

var buffer = new Buffer();
int[] alias = buffer.Data;     // alias now references the SAME array object

Array.Resize(ref buffer.Data, 5);
buffer.Data[3] = 40;
buffer.Data[4] = 50;

Console.WriteLine(buffer.Data.Length);  // 5 - buffer.Data points at the NEW array
Console.WriteLine(alias.Length);        // 3 - alias still points at the OLD array,
                                         // completely unaware a resize ever happened
Console.WriteLine(alias is buffer.Data);
// False in the sense that matters - ReferenceEquals(alias, buffer.Data) is false,
// they are now two genuinely different array objects

✅ Fix: Don’t Keep Separate References to an Array That Might Be Resized

  • After calling Array.Resize on a field or variable, re-read that field or variable again anywhere else it’s needed, rather than relying on a reference captured before the resize – that captured reference is now pointing at a stale, disconnected copy of the old data.
  • Where practical, prefer a generic List over a raw array for any collection that might need to grow or shrink – a List manages its own internal array and exposes a stable reference to the List object itself, so other code holding a reference to the list sees size changes correctly instead of being silently left behind.
  • If an array genuinely must be resized in place conceptually, make that explicit by always accessing it through a single owning object’s property or method rather than ever letting a second variable alias the underlying array directly, so there’s no second reference left around to go stale.

🚨 Why This Is Dangerous

  • Code holding what it believes is a live view of an array’s current contents, such as a cached alias inside a closure or a second field, can keep silently working against outdated data indefinitely after a resize, producing results that reflect an array state that technically no longer exists anywhere except in that one stale reference.

Array.Resize keeps its promise to the ONE reference you handed it by ref – every other reference to that same array made its own separate promise to nobody in particular, and Array.Resize never agreed to keep it updated too.

— C# Best Practice

Related posts:

C# LINQ: The Performance Traps That Cost Us 90% Speed (And How to Fix Them)

C# LINQ: The Performance Traps That Cost Us 90% Speed (And How to Fix Them)

C# — Stopwatch Is More Accurate Than DateTime

C# — Stopwatch Is More Accurate Than DateTime

C#: Fix an IAsyncEnumerable Stream Buffering Every Item Before Your foreach Loop Ever Runs Because o...

C#: Fix an IAsyncEnumerable Stream Buffering Every Item Before Your foreach Loop Ever Runs Because o...

Views: 10

Post navigation

The AI Prompt That Turns a Closet Full of Clothes Into a Capsule Wardrobe You’ll Actually Wear
Git: Fix git log Missing Commits You Know Exist Because a Shallow Clone’s –depth Cut the History Short Before Reaching Them

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (857)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (609)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (546)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (857)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com