1

How do I serialize a Generic List into a Byte Array?

public class CustomerData
{
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
    public string CustomerState { get; set; }
    public int ProductId { get; set; }
    public int QuantityBought { get; set; }
}

List<CustomerData> customerdata = new List<CustomerData>();

I know this is how to serialize a simple string into ByteArray. Trying to learn how to conduct this for more complicate lists and enumerable.

    // Input string.
    const string input = "Test";

    // Invoke GetBytes method.
    byte[] array = Encoding.ASCII.GetBytes(input);

I saw tips on on converting objects into bytes, however I am referring to generic list class.

// Convert an object to a byte array
public static byte[] ObjectToByteArray(Object obj)
{
    BinaryFormatter bf = new BinaryFormatter();
    using (var ms = new MemoryStream())
    {
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }
}
2

1 Answer 1

-1

You can do it like this:

void Main()
{
    List<CustomerData> customerdata = new List<CustomerData>();

    /*
    ...Your logic...
    ...Add Customers to List...
    */

    var binaryFormatter = new BinaryFormatter();
    var memoryStream = new MemoryStream();
    binaryFormatter.Serialize(memoryStream, customerdata);
    var result = memoryStream.ToArray();
}

[Serializable]
public class CustomerData
{
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
    public string CustomerState { get; set; }
    public int ProductId { get; set; }
    public int QuantityBought { get; set; }
}
Sign up to request clarification or add additional context in comments.

Comments