How to Convert an Object to a Byte Array in C#
By FoxLearn 1/20/2025 9:15:54 AM 1.01K
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
.
C# Object to byte array
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" }; // object to byte array c# byte[] byteArray = ObjectToByteArray(obj);
Ensure that the class you are serializing is marked with [Serializable]
if you are using BinaryFormatter
.
C# Byte array to object
To convert a byte array back into an object in C#, you can create a method that deserializes the byte array using the BinaryFormatter
.
For example, c# convert byte array to an object
// c# convert byte array to object public T ByteArrayToObject<T>(byte[] byteArray) { if (byteArray == null || byteArray.Length == 0) { throw new ArgumentException("Byte array is null or empty."); } using (MemoryStream ms = new MemoryStream(byteArray)) { BinaryFormatter formatter = new BinaryFormatter(); return (T)formatter.Deserialize(ms); } }
Usage
[Serializable] public class Customer { public int Id { get; set; } public string Name { get; set; } } public void Test() { // Original object Customer obj = new Customer{ Id = 1, Name = "Lucy" }; // Convert object to byte array byte[] byteArray = ObjectToByteArray(obj); // Convert byte array back to object Example deserializedObj = ByteArrayToObject<Customer>(byteArray); Console.WriteLine($"Id: {deserializedObj.Id}, Name: {deserializedObj.Name}"); }
The BinaryFormatter
is marked as obsolete in .NET 5 and later due to security concerns. It's better to use alternatives like System.Text.Json
, XmlSerializer
, or DataContractSerializer
if you're targeting newer frameworks or handling sensitive data.
- How to fix 'Failure sending mail' in C#
- How to Parse a Comma-Separated String from App.config in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#