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!

๐Ÿ” Navigation

๐Ÿ’ฌ Feedback
๐Ÿš€ Start Learning
Share:

Tags: