How to convert byte array to an object in C#
By FoxLearn 1/20/2025 9:15:13 AM 364
To convert a byte array back to an object in C#, you can use deserialization.
How to convert byte array to an object in C#?
For example:
public static T FromByteArray<T>(byte[] data) { if (data != null) { using (MemoryStream ms = new MemoryStream(data)) { object obj = new BinaryFormatter().Deserialize(ms); return (T)obj; } } return default(T); }
Usage
[Serializable] public class People { public int Id { get; set; } public string Name { get; set; } } //Main.cs byte[] byteArray = /* your byte array here */; People obj = ByteArrayToObject<People>(byteArray);
When using BinaryFormatter
, make sure the class is marked with [Serializable]
.
- 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#