views:

445

answers:

3

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?

+1  A: 

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

Marc Gravell
A: 

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.

D. P. Bullington
Sorry sambo99's linked blog indicates that you are wrong, you might want to update
ShuggyCoUk
+3  A: 

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.

Sam Saffron
big +1 for the link, Marshall by Bleed is interesting
ShuggyCoUk