I've been digging around the past couple hours on how to implement simple save/load functionality to a game i'm making.
The save data is being stored in a text file, during the game the player can save, storing the player & enemy positions, score etc.
I'm using StreamWriter & StreamReader for this and am having trouble deciding whether to implement this with a using statement or try-catch.
To save space i'll just list the Save methods as they're fundamentally the same as the load methods.
Using:
static void SaveAccounts(string path)
{
using (StreamWriter writer = new StreamWriter(path))
{
writer.WriteLine(accountNumber);
writer.WriteLine(name);
writer.WriteLine(address);
writer.WriteLine(balance);
}
}
Try Catch
public void Save(StreamWriter writer)
{
writer.WriteLine(accountNumber);
writer.WriteLine(name);
writer.WriteLine(address);
writer.WriteLine(balance);
}
public void Save(string filename)
{
StreamWriter writer = null;
try
{
writer= new StreamWriter(filename);
Save(writer);
}
catch (Exception e)
{
throw e;
}
finally
{
if (writer!= null) writer.Close();
}
}
In this case i've used 'accounts' in place of my sprites, just seemed simpler.
So could anyone give me any insight into which you would use? If any.
Many thanks
You should use the using
statement.
There is no reason to write 8 extra lines of code that do exact same thing, but wrongly.
There is also no reason to write 4 extra lines of code that do the same thing correctly.