-1

Is there a way I can clean this code using a c# switch expression:

bool FileOperation(string _path)
{
    bool _newDb;

    if (File.Exists(_path))
    {
        _newDb = false;
        File.Delete(_path);
    }
    else
    {
        _newDb = true;
    }

    FileStream writeStream = new FileStream(
      _path, FileMode.OpenOrCreate, FileAccess.Write);

    ReadWriteStream(
      Android.App.Application.Context.Assets.Open(sqliteFilename), writeStream);

    return _newDb;
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Alan2
  • 23,493
  • 79
  • 256
  • 450

2 Answers2

2

If you want to clean up I would rather assign the File.Exists to the _newDB variable directly instead of assigning it in the if else statement.

You can also rather use FileMode.Create instead of FileMode.OpenOrCreate, to always create a new file (and delete the old one if it exists). FileMode Enum

Example:

bool FileOperation(string _path) {
    // Setting _newDB bool equal to true if the file doesn't exist.
    bool _newDb = !File.Exists(_path);
    
    // Create new fileStream with using to dispose of it after we are done.
    using FileStream writeStream = new FileStream(
        _path, 
        FileMode.OpenOrCreate, 
        FileAccess.Write);

    ReadWriteStream(
        Android.App.Application.Context.Assets
        .Open(sqliteFilename), writeStream);

    return _newDb;
}

You could use switch expression if really wanted tough, but it's more of a workaround and definitely doesn't aid the visibility of your code.

IndieGameDev
  • 2,905
  • 3
  • 16
  • 29
1

I suggest something like the code below; I doubt if there's any need in case here:

bool FileOperation(string _path)
{
    // _newDb is true if and only if _path does not exist
    bool _newDb = !File.Exists(_path);

    // using: do not forget to dispose IDisposable (e.g. Stream)
    // FileMode.Create: create a new file or rewrite (i.e. delete and create new)
    using FileStream writeStream = new FileStream(
      _path, FileMode.Create, FileAccess.Write);

    ReadWriteStream(
      Android.App.Application.Context.Assets.Open(sqliteFilename), writeStream);

    return _newDb; 
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215