Question

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

Was it helpful?

Solution

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.

OTHER TIPS

I would use the try/catch even if it takes a few more lines. Why? Because with using you have no control of what happens when there is an exception. With try/catch you do.

As an example, imagine what happens if during the saving process there is an exception. With using the program just stops and closes the file however it is, with whatever information your program was able to write. That is, incomplete. With try/catch you can decide to delete the file. You could also write everything to a temp file and copy to the final location only if all code works fine, and if not just delete the temp file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top