user2841448 user2841448 - 1 year ago 277
C# Question

create fixed size string in a struct in C#?

I m a newbie in C#.I want to create a struct in C# which consist of string variable of fixed size. example DistributorId of size [20]. What is the exact way of giving the string a fixed size.

public struct DistributorEmail
public String DistributorId;
public String EmailId;


Answer Source

If you need fixed, preallocated buffers, String is not the correct datatype.

This type of usage would only make sense in an interop context though, otherwise you should stick to Strings.

You will also need to compile your assembly with allow unsafe code.

unsafe public struct DistributorEmail
    public fixed char DistributorId[20];
    public fixed char EmailID[20];

    public DistributorEmail(string dId)
        fixed (char* distId = DistributorId)
            char[] chars = dId.ToCharArray();
            Marshal.Copy(chars, 0, new IntPtr(distId), chars.Length);

If for some reason you are in need of fixed size buffers, but not in an interop context, you can use the same struct but without unsafe and fixed. You will then need to allocate the buffers yourself.

Another important point to keep in mind, is that in .NET, sizeof(char) != sizeof(byte). A char is at the very least 2 bytes, even if it is encoded in ANSI.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download