Cast string to variable?

Is there a way to cast a string to a variable name In my code I need to instance classes on the fly.

In psuedocode I want to do this:

Variable KeyValue<x>;

With <x> being replaced by an incrementing number on every call (so you might end up with KeyValue0, KeyValue1, KeyValue2, etc.).

Is there any way to do this in C#  I recall a way in Pascal, but that was many years ago...



Answer this question

Cast string to variable?

  • Brett A. Scudder

    Not sure what you mean. It's exactly the same with classes as with strings - after all, System.String is a class...

    Jon



  • joan_h

    Ahhh, now I understand. What's the syntax to adding to the list, though It's easy enough with strings, but I'm using classes...


  • Share me

    Storing your structure in a System.Xml.XmlDocument would work, but that's rather heavyweight if you just need an in-memory representation. If the incoming document was already in XML, then XmlDocument is the obvious choice because it will do the parsing for you as well as being an in-memory representation. Unless you need to do XMLish things with your im-memory data structure, such as XSLT transforms, XPath queries, etc., I would use an existing collection class, such as Hashtable or Dictionary<>, as Jon suggests, or write one myself*. It really depends on how you plan to use the in-memory representation. Can you give us some more information Do you need to do in-order traversal Do you need to search Do you need to render a tree Look up values at known locations within the tree


  • Mark Wheeldon

    OK, I think I've got a more constructive approach to this problem.

    How does Word manage to keep on opening new forms when I hit Ctrl+N They are instances, aren't they


  • jshunter@mngt.waikato.ac.nz

    Definitely random access. I could get away with only changing the memory storage when the file is saved, but that's clearly dangerous. I really don't know how I might end up traversing the tree though!

    I've given the storage problem a rest for now and I'm concentrating on another aspect of the program, having multiple files open in tabs (no, this isn't me going off on a tangent!). It's going well and I can create and configure my tabs and child components just how I want them. But I've run into the same problem as with the KeyValues: you have to decalare all object names at design-time. It's ridiculous! There HAS to be a way to define object names at runtime without an enourmous switch containing everything I might need. Surely there is some way


  • Jazza68

    In C#, all variable names need to be declared at compile-time. The only use of variable names is to allow programmers to hook together memory locations in meaningful ways without having to remember them. (It also allows runtime environments like the CLR to rearrange those memory locations - read GC - without you having to know that it's doing it.) If you need to refer to an arbitrary number of tabs, use collection, such as a List<> or ArrayList, to hold the dynamically sized list of TabControls. You can then refer to them positionally. Or if you want to refer to them using some string-based name, use a SortedList or SortedList<> so that you can index into the collection using a string-based key. If you need to go this route, you'll have to forego much of the design-time support supplied by Visual Studio as it was not designed for this type of scenario.

  • MRF

    Hashtables sound good, I'll have to look into them.

    I don't know what half of your questions at the end there mean, James, but what I'm ultimately aiming for is a graphical interface for the creation of the files using Windows Forms components. Instead of typing in a number, users would move a slider for example. They should also be able to create new keys or subkeys and move existing keys around the file at any point.


  • Nemorarius

    But how do I create those tab controls in the first place That's the stumbling block here.
  • Huw Parker

    Yes, they are instances. However, you don't need one variable for every instance you create. For example, if you create an ArrayList (or List<> in 2.0) you end up with references to multiple instances even though you've only got one variable (referring to the list itself).

    Jon



  • AnneR

    No, there isn't a way as the variable name must be known at compile time. You could implement this using a collection class such as:
     
    // in your constructor
    List<Variable> m_keyValueList = new List<Variable>();
    // in your method
    m_keyValueList.Add(newVariableValue);
     
    Your current "variable number" would be (m_keyValueList.Count-1).
     
    If you're using .NET Framework 1.X, you could implement the same technique using ArrayList.


  • vishalavat

    That makes sense for variables, but I simplified my example (won't be doing that again!). I'm actually parsing a text file with this pattern:

    "example"
    {
      "key1" "value1" 
      "key2" "value2" 
      "subexample" 
      { 
         "key3" "value3" 
      } 
      "key4" "value4" 
    }

    Unless I'm mistaken a list of variables isn't reliable enough, especially given subkeys. Perhaps I should widen the question to how I should store the data I've already written code to parse it, it just needs storage.

    Might System.XML help me with a little modification


  • _hunter

    My questions centred around how do you move around in your tree structure. Do you need random access to any node Or do you always start at the root and drill down
     
    From your description, I don't think a Hashtable would work because Hashtables don't have a notion of item order. For example:
      class Program {
        static void Main(string[] args) {
          Hashtable htable = new Hashtable();
          htable.Add("key1", "value1");
          htable.Add("key2", "value2");
          foreach(string key in htable.Keys) {
            Console.WriteLine(key + ": " + (string)htable[key]);
          }
        }
      }

    This prints:

    key2: value2
    key1: value1

    Probably not the order that you were expecting. Since order of the elements is probably important in your data structure, I would use a SortedList instead. Items are sorted by their keys. If you're using .NET 2.0, SortedList<> would also be a possibility.

    Another consideration in traversing your tree is how will you iterate through subkeys Will you check each type of object returned by a key and if it's a SortedList, iterate that Another possibility would be to use the Composite design pattern so that composite and leaf nodes are treated uniformly. You can find a description here:

    http://www.dofactory.com/Patterns/PatternComposite.aspx



  • SideshowBob

    It's OK, I've worked it out now. Got a few minor problems, but nothing I won't solve eventually. Thanks for all the help everyone!
  • skibumb

    XML might help, or you could use a Hashtable which had strings as keys and either strings or other Hashtables as the values.

    (If you're using 2.0 you might want to use Dictionary<> instead of Hashtable.)

    Jon



  • Cast string to variable?