How to convert an object to a byte array in C#

By FoxLearn 12/12/2024 1:18:44 AM   541
To convert an object to a byte array in C#, you can use serialization.

How to convert an object to a byte array in C#?

The most common approach to convert an object to a byte array in the .NET Framework is to use the BinaryFormatter.

This method requires the object to be marked as [Serializable], and it allows for easy serialization of the object into a byte array using a MemoryStream.

For example, c# convert object to byte array

// c# convert object to byte array
public byte[] ObjectToByteArray<T>(T obj)
{
    if (obj != null)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            new BinaryFormatter().Serialize(ms, obj);
            return ms.ToArray();
        }
    }
    return null;
}

Usage

[Serializable]
public class People
{
    public int Id { get; set; }
    public string Name { get; set; }
}
//Main.cs

People obj = new People { Id = 1, Name = "Tom" };
byte[] byteArray = ObjectToByteArray(obj);

Ensure that the class you are serializing is marked with [Serializable] if you are using BinaryFormatter.