Is it possible to save an array of objects in a separate file, and then run this file in the application and restore the array (which was in the file) from this file? (I know what you can, but how to do it)
1 answer
First, let's understand what serialization / deserialization is:
Serialization (in programming) (born serialization) is the process of translating any data structure into a sequence of bits. The inverse of the serialization operation is the deserialization (structuring) operation ( deserialization ) - restoring the initial state of the data structure from the bit sequence.
Source: Wikipedia .
We can safely replace the byte sequence with any convenient form for us (XML, JSON, etc.). I personally love JSON and for this reason I will use it in the examples.
Suppose we have a certain collection Names , which contains some objects:
List<string> Names = new List<string> { "Вася", "Петя", "Маша", "Аня" }; We need to serialize it into a convenient form and save it to a file:
* As I have already said, I will use JSON, and it is very easy to work with it using the Newtonsoft.Json library (install via NuGet).
var jsonString = JsonConvert.SerializeObject(Names); File.WriteAllText("MyData.json", jsonString); After that, we will have created a file MyData.json , which will contain our serialized object in JSON format:
["Вася","Петя","Маша","Аня"] Now we do the opposite, extract the data from the file, deserialize it and get back the List<string> :
var file = File.ReadAllText("MyData.json"); List<string> Names = JsonConvert.DeserializeObject<List<string>>(file); That's all, by such simple actions we “drive” the data into a file and then read it. The format, as well as the object can be different, this is how you learn and what is more convenient.
Good luck learning C #!