C# String CopyTo() Method

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Methods

What You’ll Learn

The instance method CopyTo() copies characters from a string into a char[] array. Unlike Copy(), which returns a new string, CopyTo() writes into a buffer you provide—useful when you need to work with individual characters, copy only part of a string, or fill a specific slot in a larger array.

01

Instance Method

text.CopyTo(...)

02

void Return

Writes to array.

03

Four Parameters

Source & dest indices.

04

Partial Copy

Any character range.

05

vs ToCharArray

When to use each.

06

Bounds Check

Size array correctly.

Definition and Usage

In C#, CopyTo() transfers characters from a string into a char[] destination. You choose where reading starts in the string (sourceIndex), where writing starts in the array (destinationIndex), and how many characters to copy (count).

Because C# strings are immutable, CopyTo() does not change the original string—it only reads from it. The destination array is mutable, so you can modify copied characters afterward (for example, encrypting or normalizing them) before building a new string with new string(buffer).

💡
Beginner Tip

If you simply need all characters in a new array, ToCharArray() is shorter: char[] chars = text.ToCharArray(). Reach for CopyTo() when you copy into an existing buffer, skip part of the string, or write at a non-zero index in the destination.

📝 Syntax

The single overload on System.String:

C#
public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count);

Parameters

  • sourceIndex — zero-based index in the string where copying begins.
  • destination — the char[] that receives characters. Must not be null.
  • destinationIndex — zero-based index in the array where writing begins.
  • count — number of characters to copy.

Return Value

void — no return value. Results appear in the destination array.

⚡ Quick Reference

GoalCode
Copy entire string to arraytext.CopyTo(0, buf, 0, text.Length)
Copy first 5 characterstext.CopyTo(0, buf, 0, 5)
Copy from middle of stringtext.CopyTo(3, buf, 0, 4)
Simple full copytext.ToCharArray()
Array back to stringnew string(buf)
Full copy
s.CopyTo(0,a,0,s.Length)

All characters

Partial
s.CopyTo(2,a,0,3)

Slice of text

ToCharArray
text.ToCharArray()

Easier full copy

Rebuild string
new string(buffer)

From char[]

Examples Gallery

Run with dotnet run. Each example shows a practical use of CopyTo()—from copying an entire string to partial ranges, buffer offsets, and comparison with ToCharArray().

📚 Getting Started

Copy all characters from a string into a char array.

Example 1 — Basic CopyTo() Usage

Copy every character from a sample string into a newly allocated array and print it.

C#
using System;

class Program {
    static void Main() {
        string sampleString = "C# is powerful!";

        char[] charArray = new char[sampleString.Length];

        sampleString.CopyTo(0, charArray, 0, sampleString.Length);

        Console.WriteLine("Copied characters:");
        Console.WriteLine(charArray);
    }
}

How It Works

The array length matches the string length. CopyTo(0, charArray, 0, sampleString.Length) reads from index 0 of the string and writes Length characters starting at index 0 of the array. Console.WriteLine(charArray) prints the array as text.

Example 2 — Copy a Portion of the String

Copy only selected characters—skip the prefix and take a substring range.

C#
using System;

class Program {
    static void Main() {
        string text = "C# Programming";

        // Copy "Program" — starts at index 3, length 7
        char[] slice = new char[7];
        text.CopyTo(3, slice, 0, 7);

        Console.WriteLine(new string(slice));
    }
}

How It Works

sourceIndex is 3 (the P in Programming). count is 7, so seven characters are copied. This is similar to Substring(3, 7) but writes into your own buffer instead of allocating a new string immediately.

📈 Practical Patterns

Buffer offsets, alternatives, and character manipulation.

Example 3 — Write at an Offset in a Larger Buffer

Combine two strings into one shared character buffer with padding between them.

C#
using System;

class Program {
    static void Main() {
        string first  = "Hello";
        string second = "C#";

        char[] buffer = new char[20];
        buffer[5] = '-';  // separator at index 5

        first.CopyTo(0, buffer, 0, first.Length);
        second.CopyTo(0, buffer, 6, second.Length);

        Console.WriteLine(new string(buffer).TrimEnd('\0'));
    }
}

How It Works

destinationIndex lets you place copied text anywhere in the array. Here first fills indices 0–4 and second starts at index 6, leaving room for a manual separator at index 5.

Example 4 — CopyTo() vs ToCharArray()

Both can produce a char array from a string—choose based on clarity and control.

C#
using System;

class Program {
    static void Main() {
        string word = "Copy";

        // Simple — entire string to new array
        char[] viaToCharArray = word.ToCharArray();

        // Explicit — same result for full copy
        char[] viaCopyTo = new char[word.Length];
        word.CopyTo(0, viaCopyTo, 0, word.Length);

        Console.WriteLine($"ToCharArray: {new string(viaToCharArray)}");
        Console.WriteLine($"CopyTo:      {new string(viaCopyTo)}");
    }
}

How It Works

For a full copy, ToCharArray() is less code. CopyTo() shines when you reuse a buffer, copy a slice, or write at a specific offset—scenarios ToCharArray() does not cover directly.

Example 5 — Modify Characters After CopyTo()

Copy to an array, change characters in place, then build a new string.

C#
using System;

class Program {
    static void Main() {
        string original = "secret";

        char[] buffer = new char[original.Length];
        original.CopyTo(0, buffer, 0, original.Length);

        // Mask every character (arrays are mutable)
        for (int i = 0; i < buffer.Length; i++) {
            buffer[i] = '*';
        }

        string masked = new string(buffer);
        Console.WriteLine($"Original: {original}");
        Console.WriteLine($"Masked:   {masked}");
    }
}

How It Works

Strings cannot be changed in place, but char[] can. After CopyTo(), you transform the buffer and create a new string with the new string(char[]) constructor. The original original string stays unchanged.

🚀 Common Use Cases

  • Character-level processing — analyze or transform text one character at a time in an array.
  • Partial extraction — copy a slice without calling Substring() first.
  • Shared buffers — fill a pre-allocated array used by APIs expecting char[].
  • Combining segments — write multiple strings into one buffer at different offsets.
  • Interop scenarios — legacy code or libraries that read/write character arrays directly.

🧠 How CopyTo() Works

1

You provide source and destination

String + indices + a char[] with enough space.

Setup
2

Runtime validates bounds

Checks that indices and count fit in both string and array lengths.

Validate
3

Characters are copied

count chars move from string index to array index.

Copy
=

Destination array updated

No return value—read or modify the array, or build a string with new string(...).

📝 Notes

  • CopyTo() returns void—results appear in the destination array.
  • destination must not be null (ArgumentNullException).
  • Ensure destinationIndex + count <= destination.Length and sourceIndex + count <= string.Length.
  • Negative indices or negative count throw ArgumentOutOfRangeException.
  • The original string is never modified—only read from.
  • For a full copy with no offset needs, ToCharArray() is often simpler.

⚡ Optimization

CopyTo() is efficient for bulk character transfer. When copying repeatedly into the same buffer, reuse the char[] instead of allocating a new array each time. For modern .NET code that only reads characters, consider ReadOnlySpan<char> as an alternative that avoids heap allocation. For beginners and typical apps, CopyTo() and ToCharArray() are both fine choices.

Conclusion

The C# CopyTo() method bridges immutable strings and mutable character arrays. It gives you precise control over which characters are copied and where they land—ideal for buffer-based workflows and character-level manipulation.

Practice the examples above, remember to size your array correctly, then continue to EndsWith() for suffix checking.

💡 Best Practices

✅ Do

  • Size the destination array before calling CopyTo()
  • Use ToCharArray() for simple full copies
  • Validate indices when copying user-controlled ranges
  • Rebuild strings with new string(buffer) when done
  • Reuse buffers in loops to reduce allocations

❌ Don’t

  • Pass a null destination array
  • Exceed string or array bounds with index + count
  • Expect CopyTo() to return a new string
  • Confuse CopyTo() with static Copy()
  • Forget that unwritten array slots keep default '\0' values

Key Takeaways

Knowledge Unlocked

Five things to remember about CopyTo()

Use these points whenever you copy string characters in C#.

5
Core concepts
📄 02

void Return

Writes to char[].

Return
✂️ 03

Partial Copy

sourceIndex + count.

Range
🔄 04

vs ToCharArray

Full copy shortcut.

Alternative
⚠️ 05

Check Bounds

Size array correctly.

Safety

❓ Frequently Asked Questions

CopyTo() copies a range of characters from a string into a char array. It is an instance method: text.CopyTo(sourceIndex, destination, destinationIndex, count). It returns void—the result lives in the destination array you provide.
source.CopyTo(sourceIndex, destination, destinationIndex, count). sourceIndex is where copying starts in the string; destination is the char[]; destinationIndex is where writing starts in the array; count is how many characters to copy.
Nothing—it has a void return type. Characters are written into the destination char array. Build a new string from the array with new string(charArray) if needed.
Copy() is static and returns a new string with the full content. CopyTo() is an instance method that writes characters into an existing char array—you control source offset, destination offset, and count.
Use ToCharArray() when you need all characters in a new array—it is simpler: text.ToCharArray(). Use CopyTo() when copying into an existing buffer, only part of the string, or at a specific offset in a larger array.
ArgumentNullException if destination is null. ArgumentOutOfRangeException if indices or count are negative, or if sourceIndex + count exceeds string length, or destinationIndex + count exceeds array length.
Did you know?

Under the hood, ToCharArray() allocates a new array and copies all characters—similar to calling CopyTo(0, array, 0, Length). The difference is convenience: CopyTo() is the lower-level API when you need control over offsets and partial ranges in an existing buffer.

Keep Building C# String Skills

Master character-array copying with CopyTo(), then continue to EndsWith() for suffix checks.

Next: EndsWith() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful