What is Span<T> in C#?
๐ก Concept: Span<T> in C#
Span<T> is a stack-only type that provides a type-safe, memory-safe representation of contiguous memory.
๐ Quick Intro
Span<T> enables working with slices of arrays and memory without allocations, improving performance.
๐ง Analogy
Like looking at a window through which you see part of a larger landscape without copying it.
๐ง Technical Explanation
- Introduced in C# 7.2/.NET Core 2.1.
- Stack-only struct type; cannot be boxed or stored on heap.
- Works with arrays, stackalloc memory, unmanaged memory.
- Allows slicing without copying.
- Improves memory and performance in high throughput scenarios.
๐ฏ Use Cases
- โ High-performance applications.
- โ Parsing protocols and data buffers.
- โ Avoiding unnecessary allocations.
- โ Working with stack-allocated memory.
๐ป Code Example
Span<int> numbers = stackalloc int[5] { 1, 2, 3, 4, 5 };
Span<int> slice = numbers.Slice(1, 3);
foreach(var num in slice) {
Console.WriteLine(num);
}

โ Interview Q&A
Q1: What is Span<T>?
A: A stack-only memory representation type.
Q2: Why use Span<T>?
A: For efficient memory management without copying.
Q3: Can Span<T> be stored on heap?
A: No, stack only.
Q4: When was Span<T> introduced?
A: C# 7.2 and .NET Core 2.1.
Q5: Can Span<T> be boxed?
A: No.
Q6: What types of memory can Span<T> represent?
A: Arrays, stackalloc, unmanaged memory.
Q7: Is Span<T> thread-safe?
A: No, generally not.
Q8: How to slice a Span<T>?
A: Using Slice method.
Q9: Can Span<T> be used with async?
A: No, because of stack-only restrictions.
Q10: How does Span<T> improve performance?
A: By reducing allocations and copies.
๐ MCQs
Q1. What is Span<T>?
- Heap object
- A stack-only memory type
- Class
- Interface
Q2. Why use Span<T>?
- For safety
- Efficient memory management
- Ease of use
- None
Q3. Can Span<T> be stored on heap?
- Yes
- No
- Sometimes
- Maybe
Q4. When was Span<T> introduced?
- C# 7.0
- C# 7.2 and .NET Core 2.1
- C# 8.0
- C# 6.0
Q5. Can Span<T> be boxed?
- Yes
- No
- Maybe
- Sometimes
Q6. What memory can Span<T> represent?
- Only arrays
- Only stackalloc
- Arrays, stackalloc, unmanaged
- Only unmanaged
Q7. Is Span<T> thread-safe?
- Yes
- No
- Depends
- Sometimes
Q8. How to slice Span<T>?
- Using Substring
- Using Slice method
- Using CopyTo
- Using Indexer
Q9. Can Span<T> be used with async?
- Yes
- No
- Sometimes
- Rarely
Q10. How does Span<T> improve performance?
- Slows down
- Reduces allocations and copies
- No effect
- Increases memory
๐ก Bonus Insight
Span<T> provides high performance for low-level memory access in safe C# code.
๐ PDF Download
Need a handy summary for your notes? Download this topic as a PDF!