Home > Articles > Programming > Windows Programming

This chapter is from the book

This chapter is from the book

Marshal-by-value objects are not remote objects. By-value objects are marked with the SerializableAttribute or implement the ISerializable interface. When a serializable object is requested from a remote server, the object is serialized into an XML or binary format and transmitted to the requester. Only data is shipped. Thus, if the serialized object has methods that need to be invoked, the code must exist on the recipient device. This is similar to how Web Services work. A Web Service returns an XML representation of an object that is comprised of data only. If you want to invoke operations on the data, you need the assembly that contains the methods. (This approach is used to return serialized data sets from an XML Web Service.)

In this section I offer another example using the Factory and Trade classes. The Factory class is a MarshalByRefObject that returns a by-value object, an instance of the serialized Trade class. In this example I need to share the implementation of the Trade class between client and server. The server will serialize a representation of the Trade class, and the client will deserialize the representation. Implicitly the deserialized data will be mapped to the shared implementation of the Trade class. The end result is that we get the data from the server—passing just the data—and reconstitute the actual object on the client.

On top of the basic example, I will provide an example of a customer version of the Trade class that implements ISerializable.

Employing By-Value Classes

In our revised example the Factory class is a marshal-by-reference class. (Recall this means that it inherits from MarshalByRefObject.) Further, I have converted the implementation of the Trade class to be a marshal-by-value class. Both classes inherit from their respective interfaces: Trade implements ITrade, and Factory implements IFactory. Interface.dll, containing the interfaces ITrade and IFactory, is shared by both client and server. On the server we configure and register the Factory class as remotable by using a .config file (as demonstrated in Listing 8.6) to manage registration of the server-activated class. As a result, only the Trade class contains modification. Listing 8.9 shows the complete, revised listing of the Trade class as defined on the server. The absence of MarshalByRefObject inheritance and the SerializableAttribute indicates that the Trade class is a by-value object in this listing.

Listing 8.9 Implementing the Trade Class as a By-Value Object

1:  <Serializable()>_
2:  Public Class Trade
4:    Private FCustomerId As Integer
5:    Private FNumberOfShares As Double
6:    Private FEquityName As String
7:    Private FEquityPrice As Double
8:    Private FCommission As Double
9:    Private FRepId As String
11:   Public Property CustomerId() As Integer
12:   Get
13:     Return FCustomerId
14:   End Get
15:   Set(ByVal Value As Integer)
16:     FCustomerId = Value
17:   End Set
18:   End Property
20:   Public Property NumberOfShares() As Double
21:   Get
22:     Return FNumberOfShares
23:   End Get
24:   Set(ByVal Value As Double)
25:     FNumberOfShares = Value
26:   End Set
27:   End Property
29:   Public Property EquityName() As String
30:   Get
31:     Return FEquityName
32:   End Get
33:   Set(ByVal Value As String)
34:     Console.WriteLine("EquityName was {0}", FEquityName)
35:     FEquityName = Value
36:     Console.WriteLine("EquityName is {0}", FEquityName)
37:     Console.WriteLine([Assembly].GetExecutingAssembly().FullName)
39:   End Set
40:   End Property
42:   Public Property EquityPrice() As Double
43:   Get
44:     Return FEquityPrice
45:   End Get
46:   Set(ByVal Value As Double)
47:     FEquityPrice = Value
48:   End Set
49:   End Property
51:   ReadOnly Property Cost() As Double
52:   Get
53:     Return FEquityPrice * _
54:       FNumberOfShares + FCommission
55:   End Get
56:   End Property
58:   Property Commission() As Double
59:   Get
60:     Return FCommission
61:   End Get
62:   Set(ByVal Value As Double)
63:     FCommission = Value
64:   End Set
65:   End Property
67:   Property RepId() As String
68:   Get
69:     Return FRepId
70:   End Get
71:   Set(ByVal Value As String)
72:     FRepId = Value
73:   End Set
74:   End Property
76: End Class

After a quick observation you will see that only the first couple of lines have changed and all the interface implementation code has been removed. Line 1 shows the use of the SerializableAttribute (defined in the System namespace), and I removed the statement Inherits MarshalByRefObject. This is all you need to do to indicate that an object can be sent back and forth in a serialized form, such as an XML document.

Additionally, the IFactory interface (not shown here, see Listing 8.1) has been modified to return a Trade value rather than the ITrade interface, and the ITrade interface—no longer required—has been removed from the Interface.vb source file.

Revising the Client to Use the By-Value Object

The client has to change very little to accommodate the marshal-by-value object. Factory is the remote object and it returns the Trade type, which we have referenced in both the client and the server. Because we are using a server-activated object—Factory—we only need to get an instance of the factory and invoke the GetTrade method. .NET automatically serializes the Trade object, and our locally declared Trade variable can handle the deserialized instance. We do not have to manage serialization on the server or deserialization on the client; this is automatic. Listing 8.10 contains the client code for the marshal-by-value Trade object.

Listing 8.10 Client Code for the By-Value Trade Object

1:  Imports System
2:  Imports System.Runtime.Remoting
3:  Imports System.Runtime.Remoting.Channels
4:  Imports System.Runtime.Remoting.Channels.Http
5:  Imports System.Reflection
6:  Imports [Interface]
8:  Public Class Form1
9:      Inherits System.Windows.Forms.Form
11: [ Windows Form Designer generated code ]
13:   Private Generator As Generator
14:   Private trade As Trade
16:   Private Sub Form1_Load(ByVal sender As System.Object, _
17:     ByVal e As System.EventArgs) Handles MyBase.Load
19:     Dim channel As HttpChannel = New HttpChannel()
20:     ChannelServices.RegisterChannel(channel)
22:     Dim Instance As Object = _
23:       Activator.GetObject(GetType(IFactory), _
24:       "http://localhost:8080/Factory.soap")
26:     Dim Factory As IFactory = CType(Instance, IFactory)
27:     trade = Factory.GetTrade(1234)
29:     trade.EquityName = "MSFT"
30:     Debug.WriteLine(trade.Cost.ToString())
31:     Generator = New Generator(Me, _
32:       GetType(Trade), trade)
33:     Generator.AddControls()
35:   End Sub
37: End Class

Note that in the example the trade variable (line 14) is declared as a Trade type. We are actually getting a serialized form of the Trade object from the server, and the client is automatically deserializing the object returned by the Factory method and reconstituting it as a Trade object. Because we have an implementation of the Trade class shared between client and server, this works nicely.

The balance of the code registers the server-activated Factory and uses the Generator class I defined to create a user interface. You can download Example4\Client.sln to experiment with this code.

Implementing ISerializable

The default behavior of the SerializableAttribute is to serialize all public properties. In a serialized form they are transmitted as public fields. However, because we have the binary code on both the client and the server, the deserialized object can be reconstituted as a complete object. Completeness, here, means that we have properties, fields, methods, attributes, and events.

Generally this default behavior is sufficient. However, it may be insufficient if you want to serialize additional data that may not be part of the public properties but is beneficial to the class or intensive to calculate. Whenever you need extra data serialized you can get it by implementing the System.Runtime.Serialization.ISerializable interface. The help documentation tells you that you need to implement GetObjectData, which is the serialization method. What is implied is that you need the symmetric deserialization behavior. Deserialization is contrived in the form of a constructor that initializes an object based on serialized data.

In order to demonstrate custom serialization in the Example4\Client.sln file I added a contrived value to the Trade class used for debugging purposes. This contrived field, DateTime, holds the date and time when the object was serialized. When a Trade object is serialized, I include the current DateTime value. When the object is deserialized, the DateTime value is written to the Debug window. To affect the custom serialization I needed to change only the shared class we have been using all along. The complete listing of the Trade class is shown in Listing 8.11 with the revisions (compared with Listing 8.9) in bold font. (The actual source is contained in Example4\Interface\Interface.vb.)

Listing 8.11 Implementing Custom Serialization for .NET Remoting

1:  <Serializable()>_
2:  Public Class Trade
3:    Implements ISerializable
   5:    Private FCustomerId As Integer
   6:    Private FNumberOfShares As Double
   7:    Private FEquityName As String
   8:    Private FEquityPrice As Double
   9:    Private FCommission As Double
   10:   Private FRepId As String
   12:   Public Sub New()
   13:   End Sub
   15:   Public Sub New(ByVal info As SerializationInfo, _
   16:     ByVal context As StreamingContext)
   18:     Debug.WriteLine("Started deserializing Trade")
   19:     FCustomerId = CType(info.GetValue("CustomerId", _
   20:       GetType(Integer)), Integer)
   21:     FNumberOfShares = CType(info.GetValue("NumberOfShares", _
   22:       GetType(Double)), Double)
   24:     FEquityName = CType(info.GetValue("EquityName", _
   25:       GetType(String)), String)
   27:     FEquityPrice = CType(info.GetValue("EquityPrice", _
   28:       GetType(Double)), Double)
   30:     FCommission = CType(info.GetValue("Commission", _
   31:       GetType(Double)), Double)
   33:     FRepId = CType(info.GetValue("RepId", _
   34:       GetType(String)), String)
   36:     Dim SerializedAt As DateTime _
   37:       = CType(info.GetValue("SerializedAt", _
   38:       GetType(DateTime)), DateTime)
   40:     Debug.WriteLine(String.Format( _
   41:       "{0} was serialized at {1}", _
   42:       Me.GetType.Name(), SerializedAt))
   44:     Debug.WriteLine("Finished deserializing Trade")
   45:   End Sub
   47:   Protected Sub GetObjectData( _
   48:     ByVal info As SerializationInfo, _
   49:     ByVal context As StreamingContext _
   50:     ) Implements ISerializable.GetObjectData
   52:     Console.WriteLine("Started serializing Trade")
   54:     info.AddValue("CustomerId", FCustomerId)
   55:     info.AddValue("NumberOfShares", FNumberOfShares)
   56:     info.AddValue("EquityName", FEquityName)
   57:     info.AddValue("EquityPrice", FEquityPrice)
   58:     info.AddValue("Commission", FCommission)
   59:     info.AddValue("RepId", FRepId)
   60:     info.AddValue("SerializedAt", DateTime.Now)
   62:     Console.WriteLine("Finished serializing Trade")
   63:   End Sub
   66:   Public Property CustomerId() As Integer
   67:   Get
   68:     Return FCustomerId
   69:   End Get
   70:   Set(ByVal Value As Integer)
   71:     FCustomerId = Value
   72:   End Set
   73:   End Property
   75:   Public Property NumberOfShares() As Double
   76:   Get
   77:     Return FNumberOfShares
   78:   End Get
   79:   Set(ByVal Value As Double)
   80:     FNumberOfShares = Value
   81:   End Set
   82:   End Property
   84:   Public Property EquityName() As String
   85:   Get
   86:     Return FEquityName
   87:   End Get
   88:   Set(ByVal Value As String)
   89:     Console.WriteLine("EquityName was {0}", FEquityName)
   90:     FEquityName = Value
   91:     Console.WriteLine("EquityName is {0}", FEquityName)
   92:     Console.WriteLine([Assembly].GetExecutingAssembly().FullName)
   93:   End Set
   94:   End Property
   96:   Public Property EquityPrice() As Double
   97:   Get
   98:     Return FEquityPrice
   99:   End Get
   100:  Set(ByVal Value As Double)
   101:    FEquityPrice = Value
   102:  End Set
   103:  End Property
   105:  ReadOnly Property Cost() As Double
   106:  Get
   107:    Return FEquityPrice * _
   108:      FNumberOfShares + FCommission
   109:  End Get
   110:  End Property
   112:  Property Commission() As Double
   113:  Get
   114:    Return FCommission
   115:  End Get
   116:  Set(ByVal Value As Double)
   117:    FCommission = Value
   118:  End Set
   119:  End Property
   121:  Property RepId() As String
   122:  Get
   123:    Return FRepId
   124:  End Get
   125:  Set(ByVal Value As String)
   126:    FRepId = Value
   127:  End Set
   128:  End Property
   130: End Class


You need to include the SerializableAttribute even when you are implementing the ISerializable interface. Remember to add an Imports statement for System.Runtime.Serialization, or use the completely qualified name for the ISerializable interface when performing custom serialization.

Serialization and deserialization in Listing 8.11 are constrained to lines 15 through 63. The recurring pattern is a constructor and a method named GetObjectData. Both the constructor and GetObjectData take SerializationInfo and StreamingContext arguments. The constructor reads the streamed field values, and the serialization method, GetObjectData, writes the fields to be streamed. Since you will be writing both the serializer and deserializer you will know the order and type of the arguments streamed.

To serialize an object, write the fields using the SerializationInfo object in the GetObjectData method. Call SerializationInfo.SetValue, passing a name for the value and the value itself. For example, line 59 passes the literal "RepId" and the value of the field FRepId. When you deserialize the object in the constructor, use the SerializationInfo argument and call GetValue. Pass the name used to serialize the object and the type information for that value. It is a good practice to perform an explicit type conversion on the return value since GetValue returns an Object type. For example, lines 33 and 34 of Listing 8.11 call GetValue, passing the literal "RepId" and the Type object for the String class, and perform the cast to String.

Line 60 demonstrates how we can serialize an arbitrary value, SerializedAt. Lines 36 through 38 demonstrate how we can deserialize that same value, perform the type conversion, and assign the value to a local variable (or a field). In lines 40 through 42 I use the value SerializedAt to indicate when the client was serialized. Perhaps such a value could be used as a rough measure of latency. If you compared the SerializedAt time with the current time, you would know how long the serialization and deserialization behavior took in a single instance.

Comparing By-Reference to By-Value Objects

There are two ways to pass objects around: by value and by reference. By-reference objects are remoted objects that inherit from MarshalByRefObject. This means that they actually exist on the remote server. By-value objects are copied to the client and use the SerializableAttribute. It's important to decide when to use either technique.

Pass objects by reference to prevent a large object from clogging network bandwidth. You will also have to pass objects by reference when the object refers to resources that exist in the server domain. For example, C:\winnt\system32 on the client is a completely different folder than C:\winnt\system32 on the server.

Consider passing objects by value when the data on the client does not need to be maintained on the server. For example, if we are simply reporting on trade information, we don't necessarily need a reference to a Trade object on the server. Using a by-value Trade object will reduce round-trips to the server since the code resides on the client.

Think of by-value objects as similar to the data returned by a Web application: It is disconnected. Think of by-reference objects as the connected model of programming.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020