Subclassing Dictionary question

Designing a new project and my internal data storage objects are subclasses of the dictionary class.

i.e.

IRDocument as dictionary creatorName as computed property (string) function get as string return lookup( "name", "" ) end function function set( value as string ) value( "name" ) = string end function

This makes it really easy to get data out of the app and write it to disk as JSON or a plist.

Now reading it back in, will give me either a JSONItem or dictionary (not using new framework), is there a neat trick to then creating a new IRDocument from a dictionary without having to copy the contents from the input dictionary?

Why not directly create a IRDocument instead of first creating a regular dictionary (“input dictionary”) and then copy everything? As IRDocument is a subclass of dictionary you just can change the type of the input dictionary where it is defined without having to change any other statements in your code.

And no, there is no neat trick to copy from dictionary A to dictionary B. You do it Key/Value-pair by Key/Value-pair or with introspection.

I’d recommend to create a regular class encapsulating a dictionary for IRDocument. You then could have a constructor taking a dictionary and you can copy all Key/Value-pairs in the constructor and forget the “input dictionary” from then on. Subclassing dictionary is “bad” IMHO (tried it, used it, replaced it with a regular class encapsulating a dictionary).

I was hoping to be able to save time and simply re-cast my subclass from a dictionary.

This might be the route I go (which I’ve used in the past), basically use a dictionary as a data store for the IRDocument class.

Problem is that IF it really comes in as a dictionary then you cant “downcast” it to your custom one as its missing relevant info
The “creatorName” is literally missing so you’ll get an illegal cast exception

[quote=285021:@Norman Palardy]Problem is that IF it really comes in as a dictionary then you cant “downcast” it to your custom one as its missing relevant info
The “creatorName” is literally missing so you’ll get an illegal cast exception[/quote]
Which is what I get :frowning:

Looks like using a dictionary as a “datastore” of my object is the way to go.