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
.
- How to use BlockingCollection in C#
- Calculating the Distance Between Two Coordinates in C#
- Could Not Find an Implementation of the Query Pattern
- Fixing Invalid Parameter Type in Attribute Constructor
- Objects added to a BindingSource’s list must all be of the same type
- How to use dictionary with tuples in C#
- How to convert a dictionary to a list in C#
- Dictionary with multiple values per key in C#
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
12/19/2024