Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

Creating an object of a variable type

I have a situation where I am saving objects to a database.

Each applicable class implements an interface (ICimeraSerializable) which has a 'serialize' function which produces a text string.

Each class also has a New(ByVal rstrData as string) sub to build an object from the serialized string.

[Side subject: you can't specify constructors on interfaces therefore how do I ensure that each class actually has an appropriate New definition?]

So to save my objects to the DB I can run code like:

For each ObjectToSave As ICimeraSerializable in MyObjects
  DBAccessor.Write(ObjectToSave.Serialize())
Next

But when I read them back from the database (using a Data Reader) I really need to be able to reconstruct the objects easily...

The first problem is that I don't know what Type they are, but this I can solve by storing some reference to the Type with the serialized object.

However, even if I do then know the Type how the blinking hell do I construct the object without using a long Select Case type statement:

Select Case objType
  Case "CI"
    deserializedObject = new CI(serializedData)
  Case "CIV"
    deserializedObject = new CIV(serializedData)
  Case etc.. etc..

which is thoroughly naff!

What I really want to do is be able to specify

  deserializedObject = new [objType](serializedData)

but of course I can't!

Now the framework will serialize automatically across different domains if you include the <Serializable()> attribute so the framework must somehow be capable of it.... but HOW?!

Help much appreciated!!!

gwyn
Friday, September 26, 2003

Take a look at the 'CreateInstance' of the System.Activator class. That should solve your problem.

Paul
Friday, September 26, 2003

Cheers Paul. It's not beautiful (because of having to determine the appropriate assembly) but it works.

gwyn
Friday, September 26, 2003

In response to your side question, there's no way to tell the compiler to force every subclass to provide the constructor.  The built-in ISerializable type has the same problem; you basically have to just document the requirement really well.

If you want to detect the problem at runtime (or as a post-build event) you can easily iterate over all the types in an assembly, and use reflection to detect subclasses without the constructor.  Not pretty.  If anyone has a better idea though, I'd love to hear it.

Joe Cheng
Tuesday, September 30, 2003

*  Recent Topics

*  Fog Creek Home