Yona
Yona

Reputation: 9702

Can I tell the CLR to marshal immutable objects between AppDomains by reference?

When marshaling objects between AppDomains in .NET the CLR will either serialize the object (if it has the Serializable attribute) or it will generate a proxy (if it inherits from MarshalByRef)

With strings however the CLR will just pass the reference to the string object into the new AppDomain. The CLR still ensures integrity since .NET strings are immutable and any change by the second AppDomain to the string will not effect the original object.

Which brings me to my question: is there a way to tell the CLR that my custom type is immutable and when used in remoting it should just pass the reference to the object as it does with the string class?

Upvotes: 12

Views: 1550

Answers (3)

Sam Saffron
Sam Saffron

Reputation: 131202

Marshalling is actually fairly tricky.

The behaviour you are describing is called "marshal-by-bleed", the runtime uses it to marshal strings (sometimes) and marshal System.Threading.Thread ALWAYS.

As far as I can tell you have no control over this (its mentioned in the article that you can define custom marshalling behaviour but I can not find any documentation on it), you could potentially pass an IntPtr around and use unsafe code to simulate this, but it smells like a huge hack to me.

Upvotes: 8

Daniel P. Bullington
Daniel P. Bullington

Reputation: 643

You only have two marshaling semantics in .NET Remoting: marshal by value (SerializableAttribute) and marshal by reference (MarshalByRef).

As you alluded to, strings are marshaled by value, as System.String is decorated with the SerializableAttribute.

If you want to pass your object between app domains and you want just a copy (no changes in on the object in the remote app domain affect the object in the local app domain) then what you want is to use the SerializableAttribute on your class.

Hope this helps.

Upvotes: -1

Marc Gravell
Marc Gravell

Reputation: 1064324

I don't think so, no. I believe that this, like the primitives, is handled directly by the runtime.

Upvotes: 0

Related Questions