473,698 Members | 2,283 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to serialize an object which refer another object?

Hi,

I have a class like the following:
class A {
private B _b;

A (B b) {
_b = b;
}
...
public B B {
get { return _b; }
}
}

and:
class B {
...
}

How to serialize an A object and B object? Maybe another serialzied
object C has
a B reference also.

Jerry
Nov 16 '05 #1
3 2385
Hi Jerry,

In the code below, notice that I used the Serializable attribute on the
types I want to serialize. Also, when I performed the serialization, I did
it on the A type, which was the root of the graph. Notice that after
serialization and deserialization that the B type that the A type references
is deserialized properly because the A type holds a reference to it.

using System;
using System.IO;
using System.Runtime. Serialization.F ormatters.Binar y;

[Serializable]
class A
{
private B _b;

public A (B b)
{
_b = b;
}

public B B
{
get { return _b; }
}
}

[Serializable]
class B
{
public string SomeVal;
}

class Test
{
static void Main()
{
B b = new B();
b.SomeVal = "I'm a B";
A a1 = new A(b);

MemoryStream memStr = null;

try
{
memStr = new MemoryStream();

BinaryFormatter binFmt = new BinaryFormatter ();

binFmt.Serializ e(memStr, a1);

memStr.Position = 0;

A a2 = (A)binFmt.Deser ialize(memStr);

Console.WriteLi ne(a2.B.SomeVal );
}
finally
{
if (memStr != null)
{
memStr.Close();
}
}

Console.ReadLin e();
}
}
Joe
--
http://www.csharp-station.com

"Jerry" <zh**********@h otmail.com> wrote in message
news:%2******** ********@TK2MSF TNGP14.phx.gbl. ..
Hi,

I have a class like the following:
class A {
private B _b;

A (B b) {
_b = b;
}
...
public B B {
get { return _b; }
}
}

and:
class B {
...
}

How to serialize an A object and B object? Maybe another serialzied
object C has
a B reference also.

Jerry

Nov 16 '05 #2
Hi Joe,

Thank you for your help. But I have another question. If I have two
object a1 and a2, the
B property of them is the same object b; e.g:
B b = new B();
A a1 = new A(b);
A a2 = new A(b);

If I serialize them and get object d_b1, d_a1, d_a2 by deserialize. d_a1.B
would not equal d_a2.B.
Acutally, I want get them same reference for d_a1.B and d_a2.B. How to do
it?

Jerry

"Joe Mayo" <jm***@nospamAt CSharpDashStati on.com> wrote in message
news:#q******** ******@TK2MSFTN GP12.phx.gbl...
Hi Jerry,

In the code below, notice that I used the Serializable attribute on the
types I want to serialize. Also, when I performed the serialization, I did it on the A type, which was the root of the graph. Notice that after
serialization and deserialization that the B type that the A type references is deserialized properly because the A type holds a reference to it.

using System;
using System.IO;
using System.Runtime. Serialization.F ormatters.Binar y;

[Serializable]
class A
{
private B _b;

public A (B b)
{
_b = b;
}

public B B
{
get { return _b; }
}
}

[Serializable]
class B
{
public string SomeVal;
}

class Test
{
static void Main()
{
B b = new B();
b.SomeVal = "I'm a B";
A a1 = new A(b);

MemoryStream memStr = null;

try
{
memStr = new MemoryStream();

BinaryFormatter binFmt = new BinaryFormatter ();

binFmt.Serializ e(memStr, a1);

memStr.Position = 0;

A a2 = (A)binFmt.Deser ialize(memStr);

Console.WriteLi ne(a2.B.SomeVal );
}
finally
{
if (memStr != null)
{
memStr.Close();
}
}

Console.ReadLin e();
}
}
Joe
--
http://www.csharp-station.com

"Jerry" <zh**********@h otmail.com> wrote in message
news:%2******** ********@TK2MSF TNGP14.phx.gbl. ..
Hi,

I have a class like the following:
class A {
private B _b;

A (B b) {
_b = b;
}
...
public B B {
get { return _b; }
}
}

and:
class B {
...
}

How to serialize an A object and B object? Maybe another serialzied
object C has
a B reference also.

Jerry


Nov 16 '05 #3
It should work if you can serialize them both in the same graph:

binFmt.Serializ e(memStr, new A[] { a1, a2 });
Console.WriteLi ne(Object.Refer enceEquals(a1.B , a2.B));

memStr.Position = 0;

A[] arr = (A[])binFmt.Deseria lize(memStr);

Console.WriteLi ne(Object.Refer enceEquals(arr[0].B, arr[1].B));

Otherwise, there isn't a way to know that a1 and a2, which were serialized
separately, originally refered to the same b.

Another thought is to implement ISerializable. Make sure every object has a
unique ID (i.e. GUID) when you serialize it and create your own mechanism to
rebuild references based on object ID.

Joe
--
http://www.csharp-station.com

"Jerry" <zh**********@h otmail.com> wrote in message
news:uz******** ******@TK2MSFTN GP14.phx.gbl...
Hi Joe,

Thank you for your help. But I have another question. If I have two
object a1 and a2, the
B property of them is the same object b; e.g:
B b = new B();
A a1 = new A(b);
A a2 = new A(b);

If I serialize them and get object d_b1, d_a1, d_a2 by deserialize. d_a1.B
would not equal d_a2.B.
Acutally, I want get them same reference for d_a1.B and d_a2.B. How to do
it?

Jerry

"Joe Mayo" <jm***@nospamAt CSharpDashStati on.com> wrote in message
news:#q******** ******@TK2MSFTN GP12.phx.gbl...
Hi Jerry,

In the code below, notice that I used the Serializable attribute on the
types I want to serialize. Also, when I performed the serialization, I

did
it on the A type, which was the root of the graph. Notice that after
serialization and deserialization that the B type that the A type

references
is deserialized properly because the A type holds a reference to it.

using System;
using System.IO;
using System.Runtime. Serialization.F ormatters.Binar y;

[Serializable]
class A
{
private B _b;

public A (B b)
{
_b = b;
}

public B B
{
get { return _b; }
}
}

[Serializable]
class B
{
public string SomeVal;
}

class Test
{
static void Main()
{
B b = new B();
b.SomeVal = "I'm a B";
A a1 = new A(b);

MemoryStream memStr = null;

try
{
memStr = new MemoryStream();

BinaryFormatter binFmt = new BinaryFormatter ();

binFmt.Serializ e(memStr, a1);

memStr.Position = 0;

A a2 = (A)binFmt.Deser ialize(memStr);

Console.WriteLi ne(a2.B.SomeVal );
}
finally
{
if (memStr != null)
{
memStr.Close();
}
}

Console.ReadLin e();
}
}
Joe
--
http://www.csharp-station.com

"Jerry" <zh**********@h otmail.com> wrote in message
news:%2******** ********@TK2MSF TNGP14.phx.gbl. ..
Hi,

I have a class like the following:
class A {
private B _b;

A (B b) {
_b = b;
}
...
public B B {
get { return _b; }
}
}

and:
class B {
...
}

How to serialize an A object and B object? Maybe another serialzied object C has
a B reference also.

Jerry



Nov 16 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
5829
by: Ian Tompsett | last post by:
H I was wondering if it possible for an object to serialize/deserialize itself from XML. I'd be guessing that it would need to use the XmlSerializer class, but that seems to want to create a brand new object when deserializing. In my case I have an existing object that I'd like to pass some XML to for the object to repopulate its member variables. Similarly I'd like it to be able to populate an XML string from the values of its member...
14
14299
by: vince | last post by:
Can I add (append) to an xml file that already contains a serialized object, and be able to deserialize to either or both objects from the same file...??? How is this done...?? thanks, vince
5
24710
by: David Sworder | last post by:
Hi, I've created a UserControl-derived class called MyUserControl that is able to persist and subsequently reload its state. It exposes two methods as follows: public void Serialize(Stream s); public void Deserialize(Stream s); Within the MyUserControl class, there is a field of type MyInnerClass
10
4155
by: Dan | last post by:
All I Am Attempting To Serialize An Object To An XML File. Here Is The Code For That public string SaveNewSurvey( MutualSurveyObject mso_TempObject, int i_JobID ) { string s_RootFileName; string s_FinalFileName; try
1
7521
by: Marcin | last post by:
hi, I would like to ask how to serialize class with members like SqlParameter. I try to use BinaryFormatter. public class Example_Class { public SqlParameter sqlParam; public Example_Class()
7
3540
by: Ben Amada | last post by:
I've created a class that I need to store in ViewState. However when I try to store it in ViewState, I get the following error: "The type 'solution.pe2' must be marked as Serializable or have a TypeConverter other than ReferenceConverter to be put in viewstate." I've included the <Serializable()> attribute, but I'm still getting the same error. The class is below ... as you can see it contains a Collection, two
1
39700
by: Tim | last post by:
Could anyone tell me what this means and how do I correct it. Any suggestions? Thanks! Tim Richardson IT Developer and Consultant www.paladin3d.com Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same
3
1271
by: Matt Fielder | last post by:
I need to find a way of serializing an object to a field in an msde table. What I'm serializing is a report definition of a 3rd party report generator. It's normally stored as a file on the local file system (has built in functionality to handle), but that's not an option for what I need. I'm familiar with using a filestream to serialize and deserialize images to the table, but this obviously isn't an image --- any help would be greatly...
3
10254
by: Julie | last post by:
Here's the scenario (public attributes, etc. omitted for brevity): class Base { } class Derived : Base { }
0
8676
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8608
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9164
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8898
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7734
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5860
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4370
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3051
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2332
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.