Sharing Enums, Class Definitions Across Assembly BoundriesHow to prevent Can't Convert Between Types Errors | | How can I pass an object from a Client application to a Remote Server Assembly and have the Remote Assembly be able to declare an instance of the object or use the same Enum on the Client and Remote Assembly?
I am writing a Client Application that needs to pass data objects and Enum types as parameters to a Remote assembly. When I declare the class or enum on the client, even when I place a copy of the enum for example into the remote assembly, I get an error telling me that I cannot convert from the Client.Enum to the Remote.Enum. How do I get around this and it will happen in VB.NET and C#?
The problem is a common one when dealing with Client Server Applications. The solution is to build a Shared DLL and reference the DLL from both the Client and Server Assemblys. I will illustrate with a simple DLL with one Enum in it and the concept will work with class, collections, enums, etc.
First, the following code shows the sample DLL code.
using System;
namespace SharedData
{
public class SharedDataObjects
{
public SharedDataObjects()
{
//
// TODO: Add constructor logic here
//
}
}
public enum BatchTimeUpdateType
{
UPDATE_BATCH_TIME=0,
UPDATE_LAST_EDIT_TIME=1,
UPDATE_LINE_COUNT_TIME=2,
UPDATE_PREPARED_TIME=4
} // enum
}
|
Next, I will make add a reference to the to the SharedData Assembly to both my Client Assembly and Server Side Assembly.
Then, I will add a using (Import in VB.NET) statement for the DLL to both the client and server classes where I want to use the shared Enum as follows:
Some usage examples of the enum will be shown below:
private BatchTimeUpdateType TimeUpdateType;
|
Here is a call to a WebService, which will finally call the remote object.
DTPWebService ws = new DTPWebService();
bool success = ws.SaveEditorWork(userID, batchID, DsJobs,
checkIN, BatchTimeUpdateType.UPDATE_LAST_EDIT_TIME);
|
Here is the signature of the remote obect, that is called by the WebService.
public bool SaveEditorWork(int userID, int batchID, DataSet ds,
bool checkIN, BatchTimeUpdateType updateTimeType)
{
}
|
Now, both the Client and Server assemblies are using the same Enum and you will not get a compile error. But if you place a copy of the same enum in both the Client and Server Assembly classes and try to use them, they will be of different types and will not compile.
Programming sure is fun... sometimes more than others.
|