CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 11 of 11
  1. #1
    Join Date
    Mar 2010
    Posts
    13

    Can't access array contents

    Hi everyone, I'm a beginner in C# and I haven't practiced programming since the days of the 8-bit computing. My project was intended to grab data from a list of filenames and store them in an array. The whole procedure was initiated after clicking on a windows form button.
    I used a structure like this:
    public struct dataDrugs
    { public StringBuilder active;
    public StringBuilder brand;
    public StringBuilder date;
    public StringBuilder path;
    }
    I instantiated the structure like this:
    dataDrugs newStruct = new dataDrugs();
    The files that interested me were stored in an array.
    And finally I used a foreach loop to extract data from the array and place them in newStruct.
    Everything went as planned and after the button click my newStruct had 79 additions :
    e.g. newStruct [78].active contained the value "amoxicillin"...
    Each new addition had to be initialized in order to avoid runtime errors. I used the StringBuilder class like this:
    newStruct[x].active= "whatever";
    I did the same for all the member of newStruct.
    The problem is that I cannot access what is stored in newStruct, outside the button_click event routine.

    I will show you some of the code I used, to make it easier to understand (I hope!!!)
    private void button1_Click (object sender, EventArgs e)
    {
    int x=0;
    byte temp=0;
    byte nameEnd=0;
    StringBuilder library=new StringBuilder ();
    StringBuilder tempStr=new StringBuilder ();
    StringBuilder finalStr=new StringBuilder ();

    FileStream myFileCreate=new FileStream (testFile, FileMode.Create);


    string [] filesPDF=Directory.GetFiles (progDir, "*.pdf", SearchOption.AllDirectories);
    string [] filesDOC=Directory.GetFiles (progDir, "*.doc", SearchOption.AllDirectories);
    int lenghtPDF=filesPDF.Length;
    int lengthDOC=filesDOC.Length;
    dataDrugs [] drugSPC=new dataDrugs [lengthDOC+lenghtPDF];

    foreach (string s in filesPDF)
    {
    tempStr.Append ("any");
    library.Append ("any");
    finalStr.Append ("any");
    tempStr.Replace (tempStr.ToString (), string.Empty);
    library.Replace (library.ToString (), string.Empty);
    finalStr.Replace (finalStr.ToString (), string.Empty);
    tempStr.Insert (0, s);
    finalStr.Insert (0, s);
    tempStr.Remove (0, 20);
    nameEnd=(byte) tempStr.ToString ().IndexOf ("_");
    drugSPC [x].brand=new StringBuilder ();// could not initialize inside struct
    drugSPC [x].active=new StringBuilder ();
    drugSPC [x].date=new StringBuilder ();
    drugSPC [x].path=new StringBuilder ();


    More code followed the above, but I guess that you get the picture.
    I tried using a class instead of the structure but it made no difference.
    I also tried to create a structure or class that contained arrays...
    like this:
    struct {
    string [] active;
    string [] brand;
    string [] date;
    string [] path;
    }
    Any suggestions?
    Also could you comment on the difference between StringBuilder and simple strings in terms of memory efficiency and speed?

  2. #2
    Join Date
    Mar 2010
    Posts
    13

    Re: Can't access array contents

    One correction:
    "Each new addition had to be initialized in order to avoid runtime errors. I used the StringBuilder class like this:
    newStruct[x].active= "whatever";
    I did the same for all the member of newStruct."
    The above statements are not correct. See the code for details. Sorry!

  3. #3
    Join Date
    Nov 2002
    Location
    .NET 3.5 VS2008
    Posts
    1,039

    Re: Can't access array contents

    Your original post is not easy to read. Please use code tags ([code] [ /code]) and more people will read it. It is also not clear whether or not you have a specific problem. The title you of your post suggests that you have a specific problem perhaps highlight that specific problem more in your description and possibly in your code. StringBuilder is good to use when you need to do lots of string concatenations for example. However I would recommend a few changes for you. You can use a class rather than a struct. You can use string rather than StringBuilder for the properties. You can still use StringBuilder to manipulate strings but once you're done with the manipulation call the ToString() method and set that against the relevant property. Just some of my thoughts...

  4. #4
    Join Date
    Mar 2010
    Posts
    13

    Re: Can't access array contents

    Code:
    private void button1_Click (object sender, EventArgs e)
    {
    int x=0;
    byte temp=0;
    byte nameEnd=0;
    StringBuilder library=new StringBuilder ();
    StringBuilder tempStr=new StringBuilder ();
    StringBuilder finalStr=new StringBuilder ();
    
    FileStream myFileCreate=new FileStream (testFile, FileMode.Create);
    
    
    string [] filesPDF=Directory.GetFiles (progDir, "*.pdf", SearchOption.AllDirectories);
    string [] filesDOC=Directory.GetFiles (progDir, "*.doc", SearchOption.AllDirectories);
    int lenghtPDF=filesPDF.Length;
    int lengthDOC=filesDOC.Length;
    dataDrugs [] drugSPC=new dataDrugs [lengthDOC+lenghtPDF];
    
    foreach (string s in filesPDF)
    {
    tempStr.Append ("any");
    library.Append ("any");
    finalStr.Append ("any");
    tempStr.Replace (tempStr.ToString (), string.Empty);
    library.Replace (library.ToString (), string.Empty);
    finalStr.Replace (finalStr.ToString (), string.Empty);
    tempStr.Insert (0, s);
    finalStr.Insert (0, s);
    tempStr.Remove (0, 20);
    nameEnd=(byte) tempStr.ToString ().IndexOf ("_");
    drugSPC [x].brand=new StringBuilder ();// could not initialize inside struct
    drugSPC [x].active=new StringBuilder ();
    drugSPC [x].date=new StringBuilder ();
    drugSPC [x].path=new StringBuilder ();
    OK, with the code. I rephrase the question: how can I access drugSPC when I'm not in the button1_click event routine?
    Why isn't drugSPC public? Or how can I make it public?

  5. #5
    Join Date
    May 2007
    Location
    Denmark
    Posts
    623

    Re: Can't access array contents

    Since drugSPC is declared within the scope of button1_Click, the .NET Garbage Collector will chew it up once that method returns. To make drugSPC available to the rest of your class, declare it as an instance variable (above the constructor):

    Code:
    public class MyClass
    {
       private dataDrugs[] drugSPC;
       public MyClass()
       {
            drugSPC = new dataDrugs [length];
       }
    }
    I would suggest using a generic List<T> in stead, as this does not require you to specify the length of the array when initializing it.
    It's not a bug, it's a feature!

  6. #6
    Join Date
    Mar 2010
    Posts
    13

    Re: Can't access array contents

    Quote Originally Posted by foamy View Post
    Since drugSPC is declared within the scope of button1_Click, the .NET Garbage Collector will chew it up once that method returns. To make drugSPC available to the rest of your class, declare it as an instance variable (above the constructor):

    Code:
    public class MyClass
    {
       private dataDrugs[] drugSPC;
       public MyClass()
       {
            drugSPC = new dataDrugs [length];
       }
    }
    I would suggest using a generic List<T> in stead, as this does not require you to specify the length of the array when initializing it.
    Thanks for the answer! Actually I already tried that (but I didn't mention it)...
    I created a constructor and passed the length of the array as a variable:
    Code:
    public class DrugData
            {
            public string [] active;
           public string [] brand;
           public string [] path;
           public string [] date;
            public DrugData (int length)
            {
            string [] active=new string [length];
            string [] brand=new string [length];
            string [] date=new string [length];
            string [] path=new string [length];
                    }
    but when I tried to use drugSPC.active[0] I got "object reference is not set to an instance of an object". I'm sure the solution is very simple, but this is litterally my first program, so please help...

  7. #7
    Join Date
    Nov 2002
    Location
    .NET 3.5 VS2008
    Posts
    1,039

    Re: Can't access array contents

    That suggests that you have declared an instace of DrugData but have not initialised it.
    Code:
    public class MyClass
    {
       // In this example I create an instance at the point of declaration.
       // You can instantiate it elsewhere but this is not a bad idea.
       // Now you can use drugSPC anywhere within this class (i.e. MyClass).
       private DrugData drugSPC = new DrugData();  
    }

  8. #8
    Join Date
    Mar 2010
    Posts
    13

    Red face I don't get it!

    I think I got the scope thing...
    Inside class + inside method = private and invisible...
    Inside class + ouside method = public or private but visible...
    Right? :$
    So I'll have to declare it outside the button_click event or the method...

    What I don't get is this:
    Code:
    public class DrugData
            {
            public StringBuilder active;
            public StringBuilder brand;
            public StringBuilder path;
            public StringBuilder date;
    
            }
    public partial class Form1 : Form
            {
            DrugData [] drugSPC;
    
    .....       .......            ......     ......
     (blah blah blah)
    .... ....                .....       ....
    private void button1_Click (object sender, EventArgs e)
                {
                getLibrary ();
                
                }
            public void getLibrary()
                {
                int x=0;
                byte temp=0;
                byte nameEnd=0;
                StringBuilder tempStr=new StringBuilder ();
    
                FileStream myFileCreate=new FileStream (testFile, FileMode.Create);
                
    
                string [] filesPDF=Directory.GetFiles (progDir, "*.pdf", SearchOption.AllDirectories);
                string [] filesDOC=Directory.GetFiles (progDir, "*.doc", SearchOption.AllDirectories);
                int lengthPDF=filesPDF.Length;
                int lengthDOC=filesDOC.Length;
    
                drugSPC=new DrugData [lengthDOC+lengthPDF];
                
    
                string [] filesALL=new string [lengthPDF+lengthDOC];
                for (int count=0 ; count<lengthPDF+lengthDOC ; count++)
                    {
                    if (count<lengthPDF)
                        {
                        filesALL [count]=filesPDF [count];
                        }
                    else
                        {
                        filesALL [count]=filesDOC [count-lengthPDF];
                        }
                    }
                foreach (string s in filesALL)
                    {
                    tempStr.Append ("any");
                    tempStr.Replace (tempStr.ToString (), string.Empty);
                    tempStr.Insert (0, s);
                    
                    nameEnd=(byte) (s.Length-4);
                    tempStr.Remove (nameEnd, 4);
                    drugSPC [x].path=new StringBuilder ();
    The above gives the error "object reference is not set to an instance of an object". This occurs because of the last line "drugSPC[x].path" which is null ! Why is it null? I used "DrugData [] drugSPC;" to declare it and "drugSPC=new DrugData [lengthDOC+lengthPDF];" to initialize it...
    When I change the class DrugData to struct DrugData like this:
    Code:
    public partial class Form1 : Form
            {
            DrugData [] drugSPC;
            
           public struct DrugData
              {
             public StringBuilder brand;
             public StringBuilder active;
             public StringBuilder date;
             public StringBuilder path;
              }
    everything works perfectly fine! Why?

  9. #9
    Join Date
    Nov 2002
    Location
    .NET 3.5 VS2008
    Posts
    1,039

    Re: Can't access array contents

    My bad. The 'struct' behaves differently from the 'class' as you don't have to instantiate it with the 'new' keyword. Hence you don't get the exception when you revert to defining DrugData as a struct. If you go for the class approach you will have to instantiate each DrugData in your array before you can use them. If you go with the struct you won't need to do that. Here's a link to the documentation on the struct

  10. #10
    Join Date
    Jun 2001
    Location
    Melbourne/Aus (C# .Net 4.0)
    Posts
    686

    Re: Can't access array contents

    I think the jist of your problem is understanding that...

    Initialising an array of objects does not initialise the individual objects in that array.
    Code:
    MyObject[] foo = new MyObject[10];
    Allocates space (initialises the array) for 10 MyObject objects, but it does not call the MyObject constructor for each one. So you would need to:
    Code:
    foreach (MyObject myObject in foo)
        myObject = new MyObject(...);
    Rob
    -
    Ohhhhh.... Old McDonald was dyslexic, E O I O EEEEEEEEEE.......

  11. #11
    Join Date
    Mar 2010
    Posts
    13

    Re: Can't access array contents

    Everything is clear now! Thanks to everybody for the help!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured