Here is the code, there are three TextBoxes, values ​​are entered into them, and Button1 saves the array in txt. In fact, the file is created, empty

public partial class Form1 : Form { public Form1() { InitializeComponent(); } public static string n1; public static string n2; public static string n3; public static string[] massiv = { n1, n2, n3 }; private void button1_Click(object sender, EventArgs e) { System.IO.File.WriteAllLines("C:\\Users\\D\\Documents\\Massiv.txt", massiv); } private void textBox1_TextChanged(object sender, EventArgs e) { n1 = textBox1.Text.ToString(); } private void textBox2_TextChanged(object sender, EventArgs e) { n2 = textBox2.Text.ToString(); } private void textBox4_TextChanged(object sender, EventArgs e) { n3 = textBox4.Text.ToString(); 
  • here is a public static string[] massiv = { n1, n2, n3 }; you added blank lines ...... when TextChanged does not automatically replace values ​​in the array, all you change is the values ​​in n1 , n2 and n3 - Aleksey Shimansky

2 answers 2

At the time of array creation

 public static string[] massiv = { n1, n2, n3 }; 

the variables n1, n2, n3 are null . Their subsequent assignment does not affect the elements of the array in any way due to the immutability of the string type.

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/string

  • null ? and I thought, by default, they were initialized with an empty string - Alexey Shimansky
  • one
    @ Alexey Shimansky No, string is a reference type, the default value is null . - Igor

Variables n1, n2, n3 are located in a completely different place of memory after their next initialization. The massiv array stores the old addresses of variables that can be changed by the time the array is used. If you do not strongly change the structure of the program, you can do this as follows:

 public static string n1; public static string n2; public static string n3; public static string[] massiv = { n1, n2, n3 }; private static void CreateArray() { //Инициализируем массив при необходимости massiv = new string[]{ n1, n2, n3 }; } private void button1_Click(object sender, EventArgs e) { CreateArray(); System.IO.File.WriteAllLines("C:\\Users\\D\\Documents\\Massiv.txt", massiv); } 
  • And if you strongly change the structure? - Dam
  • In fact, it all depends on the situation. I think that I got excited about the structure) Depending on the task of your program, you could introduce methods for checking the input strings. In the case of simple verification rules, you can represent the fields n1, n2, n3 as properties and define the verification rules in them. - Eladei