Greetings to all,
Wondering if someone can help me with a basic VS C# problem? Help much appreciated.

I can read my plain text file into an array and display one line at a time on the console with this code.

int indexInt = 0;
string fileString = "";
string[] array = new string[12]
StreamReader fileReader = new StreamReader("C:\\text.txt");
while(fileString != null)
{
     fileString = fileReader.ReadLine();
     if(fileString != null)
     {
        array[indexInt++] = fileString;
     }
}
foreach(string aString in array)
{
     Console.WriteLine(aString);
     Console.ReadLine();
} 

Basic reading of a text file into an array and reading the array to the console.

Where I run into trouble is when my array is an array of a Struct.
If I declare the following struct:

public Struct Text
{
  public string someText;
}

And an array of the struct.
public Text[] structArray = new Text[12];

I do not know how to reference structArray properly in order to load it from the file.

'structArray[ indexInt++].someText' used in the above code gives 'object reference required' error.

You can see into this example code how it has to be done:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Text[]  arrayOfText = new Text[3];
            string[] array = new string[] { "A", "B", "C" };
            
            //Adding int Text Array:
            for(int i=0;i<arrayOfText.Length;i++)
            {
                arrayOfText[i].someText = array[i];
            }

            //reading out of Text Array:
            foreach (Text _text in arrayOfText)
            {
                string myText = _text.someText;
            }
        }
    }

    public struct Text
    {
        public string someText { get; set; }
    }

and I hope it helps,
Mitja

let me see

Thanks for the quick reply.
public struct Text
{
public string[] someString;
}
gives same 'object reference required' error.

I did a mistake, sorry. Take a look ones again into my 1st post.
Mitja

I did a mistake, sorry. Take a look ones again into my 1st post.
Mitja

THANKS.
Yes, your code will help very much. I have to study it to absorb it at my level.
It works without the {set; get;} following the struct field. I have only used these in methods so far and this use is new to me. Cheers.

Get, set accessors are great option, becuase you can set it in some place, and retrive (get) it in another. So, even if you dont need it, you can still have it, and use it.
Mitja

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.