Adam Haile
Adam Haile

Reputation: 31359

SerializationException when setting instance of one class to another

I'm trying to pass an instance of a class between two separate classes, like the following.

//classes
public class A
{
  public string name;
  public string data;
}

public class B : MarshalByRefObject
{
  public A _a;
}

public class C : MarshalByRefObject
{
  public A _a;
}

//main program
static void Main(string[] args)
{
  B _b = new B();
  C _c = new C();

  _b._a = new A();

  _c._a = _b._a;
}

A exists in both classes B and C and I want to make the instance of class A that is in C equal to that instance of class A that is in B. I basically want to make sure that both B and C have the same exact copy of A.

When I try to run this, however, I get a SerializationException saying that class A is not marked as Serializable. I know I've done stuff like this before and it's never wanted it to be serialized. Why would it need this anyways? I thought that was for xml serialization.

I did try adding the [Serializable] attribute to class A, and the exception obviously went away. But after doing that, making changes to A inside of class B wouldn't then propagate to the instance of A inside of C... like they are now completely separate copies.

Any ideas?

Edit: Didn't realize that this would matter before, but after some looking around I think it does. Classes B and C inherit from the MarshalByRefObject class. Maybe this will help figure it out. I've updated the classes above.

Upvotes: 0

Views: 168

Answers (2)

Ray Booysen
Ray Booysen

Reputation: 30041

I get no such exception on the code above running in Visual Studio. I don't see any serialization occuring at all, you're simply point references at different objects.

Upvotes: 0

leppie
leppie

Reputation: 117330

I recently had a similar issue (ensuring a singleton boxed valuetype after deserialization).

To remedy my issue, I had to use ISerializationSurrogate and SurrogateSelector to fix up the reference and not let it get reboxed.

Upvotes: 1

Related Questions