Trouble initializing mixed type array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • djarvinen
    New Member
    • May 2011
    • 4

    Trouble initializing mixed type array

    C#, Visual Studio 2008, Windows Forms

    I want to initialize an array (don't care whether it is a struct or a class or arraylist or whatever).

    Here is an example of a couple of data records I would like to stuff into the array:

    Record/Item 1: foo1(), "Descriptio n 1", 0.99, true
    Record/Item 2: foo2(), "Descriptio n 2", -1.45, false
    Record/Item 3: foo1(), "Descriptio n 3", -1.00, null

    so the types I am dealing with are function, string, double, bool.

    I would like to structure it so that to enter new records by simply typing (into the source code directly!) lines like:

    { foo1, "Descriptio n 1", 0.99, true },
    { foo2, "Descriptio n 2", -1.45, false },
    { foo1, "Descriptio n 3", -1.00, null},

    etc for about 200 records, which gives me a nice visual 'table' that I can scan, modify, add to or delete from easily.

    What I do NOT want is something like:

    x.a = foo1;
    x.b = "Descriptio n 1";
    x.c = 0.99;
    x.d = true;

    where the records in the code are vertically aligned, and hard to read and edit.

    I've struggled quite a bit trying to find a 'wrapper' that will use the format described above but always seem to end up in a dead end.

    Any help would be appreciated.

    Thanks.
    Last edited by Niheel; May 5 '11, 05:36 PM. Reason: Unnecessary spacing, fixed. thanks for posting your question :)
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    What about an array of object type?

    Code:
    object[] objArray = { ... };
    You can also use an ArrayList object as well, which provides some of the List<T> functionality.

    Comment

    • djarvinen
      New Member
      • May 2011
      • 4

      #3
      Object arrays or ArrayList 'may' be the way to go but I couldn't find a way to initialize one 'line' of the list with different type objects.

      I did find this class definition example which is very close to what I want:
      Code:
      private class Cat
              {
                  public int Age { get; set; }
                  public string Name { get; set; }
              }
              List<Cat> cats = new List<Cat>
              {
                  new Cat(){ Name = "Sylvester", Age=8 },
                  new Cat(){ Name = "Whiskers", Age=2 },
                  new Cat(){ Name = "Sasha", Age=14 }
              };
      Each line of 'new Cat()' above defines all the properties of Cat in one line (and is obviously easily extendable), but it is a bit of a nuisance to have to add "Name =", "Age =", etc for each cat property. My ideal solution would be to have the initialization lines look like:

      { "Sylvester" , 8 },
      { "Whiskers", 2 },
      etc

      but the solution in C# continues to elude me.
      Last edited by Niheel; May 5 '11, 05:36 PM. Reason: Unnecessary spacing and added code tags to display code.

      Comment

      • GaryTexmo
        Recognized Expert Top Contributor
        • Jul 2009
        • 1501

        #4
        You can so initialize one line with an ArrayList or an array of objects...

        Code:
        object[] o1 = { "Sylvester", 8 };
        That's a full line exactly as you're asking for it.

        For multiple lines...
        Code:
        List<object[]> cats = new List<object[]>();
        cats.Add(new object[] { "Sylvester", 8 });
        cats.Add(new object[] { "Whiskers", 2 });
        
        foreach (object[] cat in cats)
        {
            Console.WriteLine("Cat");
            foreach (object o in cat)
            {
                Console.WriteLine("\t" + o.ToString());
            }
            Console.WriteLine();
        }
        That said, why do you need to initialize it like that? Why can't you have an object of type Cat with properties in it? If you're just trying to save yourself some typing at the expensive of good coding practices, that might not be a good idea...

        Comment

        • djarvinen
          New Member
          • May 2011
          • 4

          #5
          Great, that works exactly as I wanted.

          As to 'saving typing at the expense of good programming practices'...

          Well, I know I had done something like this several years before (adding function pointers, string data, etc to a single table) very simply (don't even remember the language or version I used back then), and I was just trying to mimic that behavior as well.

          The data that I have to use is already in a form of
          'tabpage, string, bool, string, etc' and in that form, I can easily just copy and paste it into my object array definition.

          In the class definition listed above (in the cats example), I would have to add 'objectname =' in front of every item in the table which would be irritating as well as making it less readable (the items would scroll off the right side of the screen, among other things).

          I really don't see where the 'expense of good coding practices' comes into play. I was just trying to do something I had done before, and the C# language seemed to hamstring me a bit in a place where it really didn't need to; does it really 'need' "age=", "name=", etc. It seems that the definition of those types had already been defined, and the order of the objects would define what type was being initialized. That's the way it used to work, and I find it frustrating I have to learn entirely new constructs every time the language (or even the version!) changes. (Insert long rant here about C++, C# designers taking away functionality, changing constructs, modifying behavior and adding complexity in the name of some obscure programming god called oop but I'm sure we can save that for another day and another thread).

          But regardless, thanks for taking the time to post and for the helpful suggestions.

          Comment

          • GaryTexmo
            Recognized Expert Top Contributor
            • Jul 2009
            • 1501

            #6
            Well, it needs them because it needs to know what to assign where. Like, what if you had this...

            Code:
            public class Person
            {
              public string FirstName { get; set; }
              public string Lastname { get; set; }
            }
            How would your code tell the difference between the following...
            Code:
            Person p1 = { "Gary", "Texmo" };
            Person p2 = { "Texmo", "Gary" };
            As far as matching types go, both are strings, so unless you explicitly specify the name of the property in the instantiation, it doesn't know which string data represents the first name and which the last name. At this point you might think, well why can't it just assign them using the order they were defined in the class by? That's probably what this other language (a struct in C/C++ sounds like...?) did, but if you think about it for a little while it's actually a bit of a maintenance nightmare.

            A lot of people organize their properties either alphabetically, or in some kind of logical grouping when they code. If later on you decide you're going to add a property to the class and you don't put it at the end, you'll immediately mess up the definitions that might exist elsewhere in your code, and that's outright assuming it would ignore ones that weren't defined at the end.

            I understand that you want to copy/paste your old code, but is it really that much work? Using the object names will make your code much easier to maintain in the future, and the cost (while a little tedious) isn't that much. That said, if it really is a ton of code, you can always write a short little program to insert the property names into the definitions and then output the new code to a textbox, at which point you can copy/paste. And in actuality, putting those property names in your definition makes your code more readable because you or anybody else reading it in the future will automatically know what data goes with which property :)

            The reason using the object array that I've specified may not be preferable is that the type information isn't as obvious. Everything in the array is of the base class object, so it might not be obvious that data that is 3.4 is type double or float, for example. You can get the type out of the code by using the GetType method, but it just makes things a little more difficult on you.

            That said, ultimately it's about what you're comfortable with. I can point out a best practice, but if you don't like it that's fine, it's your code to write :) I do advise caution against the "it's just easier" thing though... ultimately you or someone else will have to maintain your code at some point in time so making thing things a little easier on yourself or them is definitely a worthwhile thing.

            I'm not trying to attack you or your code here, I just want to give you some things to think about. Good luck with your project! :)

            Comment

            • djarvinen
              New Member
              • May 2011
              • 4

              #7
              Oh, sorry, I didn't think it was an attack. :) I just haven't explained very well the 'back story'.

              The data itself is not from 'old code'. It is actually a table from a document which defines alarms, messages for each alarm, I/O points associated with the alarm, etc.

              It is presented in a very clear and organized way. By just copying and pasting the data, that structure would be retained, and easily understood by anyone else who were to pick up the project code.

              The only changes likely would be to fix typos, perhaps change some messagesto make things clearer, and possibly add a few alarms at a later date. It's all pretty much fixed in stone; I just had to add the data to the program that would display the alarm, the type of alarm, and message about what to do with the alarm.

              To me, the programming 'work' is done in how to handle any generic alarm and not have to have specific code for any individual alarm. The data can then just be stuffed into the code and pretty much forgotten.

              As far as programming practices, if it is easy to read, easy to understand, and easy to maintain, then I have pretty much done my job. :)

              Comment

              • bvrwoo
                New Member
                • Aug 2011
                • 16

                #8
                It is better to write a struct or a class for this because you are encapsulating. When you insert a struct as an object (goes on the heap) is has to be boxed and then unboxed when you cast it back. This is overhead. Make the struct using good programming practices.

                Comment

                Working...