diff --git a/csharp/src/Google.Protobuf/WritingPrimitives.cs b/csharp/src/Google.Protobuf/WritingPrimitives.cs index 823cdb7f49db..70f96e965de8 100644 --- a/csharp/src/Google.Protobuf/WritingPrimitives.cs +++ b/csharp/src/Google.Protobuf/WritingPrimitives.cs @@ -182,7 +182,8 @@ public static void WriteString(ref Span buffer, ref WriterInternalState st // If 64bit, and value has at least 4 chars, process 4 chars at a time. if (IntPtr.Size == 8 && value.Length >= 4) { - ref byte sourceBytes = ref Unsafe.As(ref MemoryMarshal.GetReference(value.AsSpan())); + ref char sourceChars = ref MemoryMarshal.GetReference(value.AsSpan()); + ref byte sourceBytes = ref Unsafe.As(ref sourceChars); ref byte destinationBytes = ref MemoryMarshal.GetReference(buffer.Slice(state.position)); // Process 4 chars at a time until there are less than 4 remaining. @@ -201,7 +202,7 @@ public static void WriteString(ref Span buffer, ref WriterInternalState st // so use them to perform array operations without bounds checks. for (; currentIndex < length; currentIndex++) { - Unsafe.AddByteOffset(ref destinationBytes, (IntPtr)currentIndex) = Unsafe.AddByteOffset(ref sourceBytes, (IntPtr)(currentIndex * 2)); + Unsafe.AddByteOffset(ref destinationBytes, (IntPtr)currentIndex) = (byte)Unsafe.AddByteOffset(ref sourceChars, (IntPtr)(currentIndex * 2)); } } else