How to Convert an Object to a Byte Array in C#
By FoxLearn 2/12/2025 1:42:17 AM 2.07K
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 // c# class to byte array public byte[] ObjectToByteArray<T>(T obj) { if (obj != null) { using (MemoryStream ms = new MemoryStream()) { // c# serialize object to byte array new BinaryFormatter().Serialize(ms, obj); // c# to byte array 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)) { // c# deserialize byte array to object 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.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#