Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I create a static array containing my custom class?
    text
    copied!<p>I have a method that returns an array of custom class objects that are created by parsing a text file. At the moment every time I use it I am rereading the file which isn't very efficient.</p> <p>What I wat to do is create an array containing the objects when the page loads and store them in an array which can then be used later.</p> <p>The method is:</p> <pre><code>public Album[] readArray(string sTextFilePath) { string[] allLines = File.ReadAllLines(Server.MapPath(sTextFilePath)); Album[] Albums = new Album[allLines.Length]; for (int i = 0; i &lt; allLines.Length; i++) { string[] lineSplit = allLines[i].Split(','); Albums[i] = new Album(); Albums[i].ID = Convert.ToInt32(lineSplit[0]); Albums[i].title = lineSplit[1]; Albums[i].keyName = lineSplit[2]; } return Albums; } </code></pre> <p>and the class is simple, just:</p> <pre><code> public class Album { public int ID { get; set; } public string title { get; set; } public string keyName { get; set; } } </code></pre> <p>I thought I could create the static object using something like:</p> <pre><code>static Album myAlbums[] = readArray("Albums.txt"); </code></pre> <p>but I am getting the following error:</p> <p><strong>A field initializer cannot reference the nonstatic field, method, or property 'B2M._Default.readArray(string)'</strong></p> <p>I am new to C# so this is probably something dumb. (Feel free to poke fun in my general direction if this is the case!)</p> <p>Thanks in advance for any assistance,</p> <p>Ben</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload