Don't Do This When Using a C# Span – It Is a Bug #shorts



Imagine having a List, and you wish to operate on it as quickly as possible. Apparently, the best way to modify an existing content of a list is to marshal it to a span. Then do whatever you wanted using the span to access the data.
But beware! The span is holding a reference to the underlying array structure inside the list. You must not do anything that may cause that array’s reallocation until you are over with the span!
Do not add items to the list. Do not remove items from the list. Those two operations may cause reallocation of the underlying array and the span will access stale data.
It is safe to change the items in the list, though. But… why, when you already have a fast alternative to that through the span you already possess.

Video courses:
Beginning Object-oriented Programming with C# ► https://codinghelmet.com/go/beginning-oop-with-csharp
Collections and Generics in C# ► https://codinghelmet.com/go/collections-and-generics-in-cs
Making Your C# Code More Object-oriented ► https://codinghelmet.com/go/making-your-cs-code-more-oo

Other courses at Pluralsight ► https://codinghelmet.com/go/pluralsight
Other courses at Udemy ► https://codinghelmet.com/go/udemy

Additional videos:
Want to Start with DDD? Try Ubiquitous Language First! ► https://youtu.be/_zWMjMUHinc
Using C# Record Types ► https://youtu.be/VouNkrgkH78
Covariance and Contravariance in C# ► https://youtu.be/Wp5iYQqHspg
How do Virtual Functions Work? ► https://youtu.be/b0IDTWoaUJ0

Practical Design playlist at YouTube ► https://youtube.com/playlist?list=PLSDYwLgFqaX78eEg_YKs0wHmOMi7_ggZr