Before that I wrote on D, and it's a bit complicated to understand how to do the same thing in C #.

The bottom line. I need an array of structures. The structure itself is a description of the fields in the database. Those. I want to write all the data from the database into an array of structures. How to do it right?

struct UserData { public int id; public string guid; public string name; public byte[] userblob; }; public void PGConnect() { UserData [] uds; UserData ud; // с одной структурой все работает, но мне нужен масив, я его объявил выше NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5433;User Id=" + config.PGLogin + ";" + "Password=" + config.PGPass + ";Database=" + config.PGdbName + ";"); try { conn.Open(); } catch(SocketException e) { Console.WriteLine(e.Message); } // NpgsqlCommand command = new NpgsqlCommand("SELECT city, state FROM cities", conn); string commandText = @"SELECT id, guid, username, userblob FROM ""USERS"" "; NpgsqlCommand command = new NpgsqlCommand(commandText, conn); try { NpgsqlDataReader dr = command.ExecuteReader(); while (dr.Read()) { //ud.id = Int32.Parse(dr[0].ToString()); //ud.guid = (dr[1].ToString()); //ud.name = (dr[2].ToString()); //ud.userblob = (byte[])dr[3]; //а в массив как? } } finally { conn.Close(); } } 

    1 answer 1

    To allocate memory for an array, you need to know its length, and you don’t know it in advance. Fill out the list:

     List<UserData> uds = new List<UserData>(); ... while (dr.Read()) { UserData ud; ud.id = Int32.Parse(dr[0].ToString()); ud.guid = dr[1].ToString(); ud.name = dr[2].ToString(); ud.userblob = (byte[])dr[3]; uds.Add(ud); } 

    If the result is necessarily needed as an array:

     return uds.ToArray(); 
    • and how UserData ud differs from UserData ud = new UserData(); ? And how does my ad uds differ from yours? It seems to be compiled and the examples of the network saw that I can. - Dmitry Bubnenkov
    • @Suliman: UserData ud declares a variable, but does not initialize it. new UserData creates a new value (unlike C ++, not necessarily on the heap), which can initialize the variable. The same applies to arrays (which are reference types in C #, that is, the variable contains not the array itself, but only a reference to it). - VladD
    • @VladD, and the bad is not initialized variable? If I need a function to return an array of structures, then how do I write? - Dmitry Bubnenkov
    • @Suliman - In your case with the structure, indeed, new can not be called. .NET itself will "zakorobchit" within List<>.Add . - Igor
    • @Suliman: Well, if you initialize all the fields manually, you can use. But to use an uninitialized variable C # will not give you. (This even in C ++ has undefined behavior.) - VladD