Thought for a write-once constant class

Yeah, that is the drawback to the scheme, but still easier than a computed property and not as easy to replace the value as in a static.

I put a little something together. It’s a module with a GlobalDynamicConstant method like I described above, but also a method LocalDynamicConstant(o as object) that keeps track of separate class instances (by a dictionary of weakrefs) for each object it is called with. The drawback is that any object can read the constants from any other object, and there is no autocomplete/syntax check like with a local constant/variable… but in any case, it’s interesting. You could change it to use variants if you wanted to store more than strings…

You can call
LocalDynamicConstant(me).someValue=“A value to store”
and
x=LocalDynamicConstant(me).someValue
I don’t see an easy way to disturb the value once it’s been set since it resides in a protected property of a global module.
http://www.pidog.com/share/dynconst.xojo_binary_project

Very nice.

A couple of suggestions:

If you try to assign a value to a “constant” that’s already assigned, it should raise an exception. The developer needs to know he made a mistake.

I’d modify LocalDynamicConstant like this:

  if ObjectRefs=nil then ObjectRefs=new Dictionary
  
  dim keys() as Variant = ObjectRefs.Keys
  for each ref as WeakRef in keys
    dim testObject as Object = ref.Value
    if testObject=o then Return ObjectRefs.Value(ref)
    if testObject=nil then ObjectRefs.Remove ref
  next
  
  dim mref As new WeakRef(o)
  dim dc as new DynamicConstant
  ObjectRefs.Value(mref)=dc
  Return dc

My concern is that, if this is used heavily (lots of different objects), it will get slow because of the loop.

Also, you can’t change the constant on every run of the method within the same instance. I’m not sure that’s a big deal, though.