C# & ADO.NET

Strings in C, C++ and C#: what .NET developers should know when reading native code

C# & ADO.NET · · Published 2026-12-02 · Updated 2026-12-02

Sooner or later a .NET developer opens a C header file: a vendor SDK, a Windows API signature, a legacy DLL that a Web Forms site still calls through P/Invoke. The word "string" means three different things in C, C++ and C#, and most interop bugs (garbled accents, truncated text, crashes on long input) come from mixing them up. This comparison explains how each language stores text, then what the .NET runtime does when a C# string crosses into native code.

Three languages, three ideas of a string

CC++C#
Basic typeNo string type: an array of charstd::string (a class template, std::basic_string<char>)string = System.String
How the end is foundA terminating '\0' byteStored length (and a '\0' kept after the data for c_str())Stored length
Mutable?Yes, the buffer is just memoryYesNo, every change produces a new string
MemoryManaged by hand (stack array or malloc/free)Owned by the object, freed by its destructorGarbage-collected
EncodingNot defined by the type: bytes in whatever encoding the program usesSame as C for std::string; std::wstring holds wchar_tUTF-16 code units
Can contain a zero character?No, it ends the stringYesYes

The last two rows cause most of the trouble. A C function only sees bytes up to the first zero, and it has no idea which encoding those bytes are in. C# knows both the length and the encoding, because Microsoft's reference for System.String defines a string as a sequential collection of UTF-16 code units.

C: char arrays and the null terminator

In C, "hello" is an array of six bytes: five letters and a zero. Functions such as strlen, strcpy and strcat walk the memory until they meet that zero. Nothing records the size of the buffer, so copying a long string into a short array silently writes past its end: the classic buffer overflow. Microsoft's C runtime added "secure" variants that take the destination size, such as strcpy_s and wcscpy_s, and you will see them in a lot of Windows code.

char name[16];
strcpy_s(name, sizeof name, "Postback");   /* fails safely if the text is too long */
size_t n = strlen(name);                    /* 8: the terminator is not counted */

When you read a C signature, two habits help. First, look for a pointer and a length travelling together (char *buf, size_t len): that is how C passes a buffer to fill. Second, read the comment or documentation to learn who frees the memory. If the library returns a char* it allocated, it usually exports a matching "free" function, and your C# code has to call it.

C++: std::string, std::string_view and friends

C++ wraps the buffer in a class. A std::basic_string object knows its length, grows when you append, and frees its memory when it goes out of scope. It is mutable, unlike a C# string: s += "x" changes the same object. s.c_str() returns a pointer to a zero-terminated copy of the data for functions that still expect C strings.

C++17 added std::string_view, a pointer plus a length that refers to characters owned by someone else. It is the closest relative of C#'s ReadOnlySpan<char>: cheap to pass around, but only valid as long as the original text lives. A string_view is not guaranteed to be followed by a zero, so passing view.data() to a C function is a bug waiting to happen.

std::string s = "Postback";
s += " Notes";                       // modifies s in place
std::string_view first(s.data(), 8); // "Postback", no copy
const char* p = s.c_str();           // zero-terminated, valid while s is unchanged

Windows code: wchar_t, TCHAR and BSTR

Windows adds its own layer, and it is the one ASP.NET developers meet most often. Microsoft's guide to working with strings in Win32 explains the conventions:

Microsoft's C++ documentation has a full page on converting between these string types, useful when you have to wrap a library yourself.

The practical rule for .NET: a C# string is UTF-16, the same representation as wchar_t on Windows. Calling the W version of an API is the natural fit; calling the A version forces a conversion to the ANSI code page, which loses every character that code page cannot represent.

What happens when a C# string crosses into native code

A P/Invoke declaration tells the runtime how to convert a string argument. With [DllImport], that is the CharSet field. Microsoft's page on charsets and marshalling gives the trap in one sentence: C#, Visual Basic and F# "use the None charset by default, which has the same behavior as the Ansi charset". On Windows that means the system code page; on Linux with .NET Core 3.0 and later it means UTF-8.

// Matches a native function declared as: int count_chars(const wchar_t* text);
[DllImport("legacy.dll", CharSet = CharSet.Unicode)]
static extern int count_chars(string text);

// .NET 7 and later: source-generated, encoding stated explicitly
[LibraryImport("legacy.dll", StringMarshalling = StringMarshalling.Utf16)]
internal static partial int count_chars(string text);

On .NET 7 and later, Microsoft recommends [LibraryImport], which generates the marshalling code at compile time; the source generation guide shows the StringMarshalling setting and the matching MarshalAs attributes. Web Forms sites on .NET Framework 4.8 keep using [DllImport]; set CharSet every time rather than relying on the default.

Match the setting to the native type:

Native parameterC# declaration
const wchar_t*, LPCWSTRstring with CharSet.Unicode or StringMarshalling.Utf16
const char* documented as UTF-8string with StringMarshalling.Utf8 or [MarshalAs(UnmanagedType.LPUTF8Str)]
const char* in the ANSI code page (old Windows DLLs)string with CharSet.Ansi, and test with accented text
BSTR[MarshalAs(UnmanagedType.BStr)] string
char* buf, int len filled by the calleea char[] or byte[] buffer, not a string

Getting text back: buffers, StringBuilder and returned pointers

Old samples pass a StringBuilder for output buffers. It works, but Microsoft's native interoperability best practices explain that it costs four allocations per call and recommend a character buffer from ArrayPool instead. The same page warns never to use [Out] string parameters: native code that writes into a string can corrupt an interned string shared by the whole process.

[DllImport("legacy.dll", CharSet = CharSet.Unicode)]
static extern int get_label(char[] buffer, int size);

char[] buf = ArrayPool<char>.Shared.Rent(256);
try
{
    int written = get_label(buf, buf.Length);
    string label = new string(buf, 0, written);
}
finally { ArrayPool<char>.Shared.Return(buf); }

When a native function returns a pointer it allocated, declare the return type as IntPtr, convert it with Marshal.PtrToStringUTF8 (or PtrToStringUni for UTF-16), then call the library's own free function. Declaring the return type as string makes the runtime free the memory with the COM allocator, which crashes if the library used malloc.

A checklist for reading a native signature

  1. Is the character type char or wchar_t? That decides between UTF-8/ANSI and UTF-16.
  2. If it is char, does the documentation say UTF-8? If not, assume the ANSI code page on Windows and test with "é", "ß" and "€".
  3. Is the parameter const? Input only: a string is fine. Not const: the callee writes, so pass a buffer and its size.
  4. Who frees returned memory? Find the matching free function before writing the declaration.
  5. Can the text contain a zero character? C will cut it there; C# will not.

For the managed side of the same questions, our guide to working with strings in C# covers comparison, splitting and conversion, and string vs StringBuilder explains why C# strings are immutable in the first place. The broader language differences between C and C++ are in our C vs C++ comparison.