The SLAR (vol2) on System.Runtime.InteropServices.CharSet

Continuing in the series sharing some of the information in the .NET Framework Standard Library Annotated Reference Vol 1 and .NET Framework Standard Library Annotated Reference Vol 2 with some information on CharSet.


public enum CharSet


CF Ansi = 2,

Auto = 4,

MS CF None = 1,

Unicode = 3,





It’s somewhat unfortunate that CharSet.Ansi is the default behavior for PInvoke, since

managed strings and characters are internally Unicode. Win32 APIs often expose both an ANSI

and Unicode export, but by default you end up calling the ANSI one, requiring the Interop

marshaler to copy each Unicode string to a new ANSI string! In contrast, by calling the Unicode

export, the CLR can just pin the managed strings and expose them directly. You can override

the default behavior and explicitly mark each PInvoke signature with CharSet.Auto,

although in the future the CLR will provide a module-level DefaultCharSetAttribute that

allows you to select your own default for all signatures in your module.



BTW – if you like Adam’s take on the world, check out his exhaustive book on Interop…

.NET and COM: The Complete Interoperability Guide

Comments (1)

  1. Kevin Westhead says:

    Another comment about this enum is that it doesn’t have a member for zero, which breaks the enum design guidelines (see Instead, the None member has a value of 1 and this means you can have a situtation where the default value assigned by the CLR is not a member of the enum. E.g. the following ctor will output "False":

    internal class CharSetTest


    private CharSet m_charSet;

    public CharSetTest() : base()


    Debug.WriteLine(Enum.IsDefined(typeof(CharSet), m_charSet).ToString());



    Having said that, I doubt this enum is used much outside of the existing interop attributes, so it’s unlikely to be a problem.

Skip to main content