Saving And Loading List error
HI My problem is how to save and load a List that contains some record os a custom class.
i have a class of type Info
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[Serializable]
public class Info {
public string name;
public string surname;
public string phone;
public Info(string newname, string newsurname, string newphone){
name = newname;
surname = newsurname;
phone = newphone;
}
}
in my code i have a a list public List<Info> Infodb = new List<Info>();
that have some records and i want to be able to save and load that record
so i have create thees to code parts to save and load
Save
try{
FileStream fs = new FileStream(mySavePath + "db.db",FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize (fs, Infodb);
fs.Close();
} catch {
Debug.Log ("Cannot save list to file");
}
and for load
public List<Info> Load(){
if (File.Exists (mySavePath + "db.db")) {
FileStream fs1 = new FileStream(mySavePath + "db.db",FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
List<Info> people = bf.Deserialize (fs1) as List<Info>;
fs1.Close();
return Infodb;
}
}
I am not sure that this is the correct way to do it and also i get a debug error error CS0161: `myfile.Load()': not all code paths return a value
what i need to do is be albe to save the items of my list Infodb to a file
and the be able to load that file and fill that list again
thanks in advanced :)
Answer by MacDx · Jun 06, 2018 at 10:15 PM
CS0161 Is a compiler error. And just like it says, the method needs a return statement on every code path.
When you wrote
public List<Info> Load() {...} //Load method
You committed to return a List<.Info.> value. But in the method implementation you wrote, what would happen if File.Exists() evaluated to false? What would you return then? That's where the return statement is missing (outside of your if). The compiler will not guess what you want to return in said case so it throws error.
Hope this helps!
mAD X thanks for the info.
the error is solved but my algorithm still does not load the values
Hmmm I just noticed that in your Load() method you are returning Infodb. Shouldn't you be returning the local variable people ins$$anonymous$$d? Since that's where you assigned the result of Deserialize().
Your answer
Follow this Question
Related Questions
How can I save this objects ? 0 Answers
How Do I Create a List of Two Strings? C# 1 Answer
Updating a List from a Custom Inspector 0 Answers
Firebase List Users 1 Answer
list.contains problem 1 Answer