Trying to Serialize an object into a varbinary RRS feed

  • Question

  • I have a class "EmployeeTree" I have an object of the class named "employeeTree" I want to pass this "employeeTree" as a parameter to a Stored Procedure as a varbinary, how can I convert the object into varbinary?

    (and how can I later retrieve the varbinary and convert it into the object)?

    • Edited by avivgood Friday, November 15, 2019 4:11 AM
    Friday, November 15, 2019 4:09 AM


  • Hi avivgood, 

    Thank you for posting here.

    For your question, you want to serialize an object into a varbinary and then convert the varbinary to object.

    I make a test on my side, and you can refer to the following code.

    EmployeeTree Class.

       [Serializable] // mark it as serializable.
        class EmployeeTree
            public int Property1 { get; set; }
            public string Property2 { get; set; }


            static byte[] SerializeClass(EmployeeTree et)
                byte[] data;
                using (MemoryStream ms = new MemoryStream())
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(ms, et);
                    ms.Position = 0;
                    data = ms.ToArray();
                return data;
            static EmployeeTree DeserializeClass(byte[] data)
                EmployeeTree et;
                using (MemoryStream ms = new MemoryStream(data))
                    BinaryFormatter formatter = new BinaryFormatter();
                    et = (EmployeeTree)formatter.Deserialize(ms);
                return et;
            private void button1_Click(object sender, EventArgs e)
                EmployeeTree et = new EmployeeTree() { Property1 = 1,Property2 = "A" };
                byte[] result = SerializeClass(et);
                EmployeeTree etResult = DeserializeClass(result);


    Hope it can help you.

    Best Regards,

    Xingyu Zhao

    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by avivgood Saturday, November 16, 2019 7:07 PM
    Friday, November 15, 2019 7:04 AM