Skip to content

Instantly share code, notes, and snippets.

@pvginkel
Created July 5, 2017 06:44
Show Gist options
  • Save pvginkel/56658191c6bf7dac23b3893fa59a35e8 to your computer and use it in GitHub Desktop.
Save pvginkel/56658191c6bf7dac23b3893fa59a35e8 to your computer and use it in GitHub Desktop.
// The proposed syntax:
using (File.Open(this.DataSourceFileName, FileMode.Open, FileAccess.Read))
{
}
return true;
// This is the same as writing the code below. See
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement for
// an explanation.
FileStream tmp1 = File.Open(this.DataSourceFileName, FileMode.Open, FileAccess.Read);
try
{
}
finally
{
if (tmp1 != null)
((IDisposable)tmp1).Dispose();
}
return true;
// The finally can normally be reached in two ways:
//
// * When an exception is thrown in the try; or
// * When the try completes normally.
//
// Since there is no code in the try, the first case doesn't apply, so only the second case applies.
// The code can thus be simplified as:
FileStream tmp1 = File.Open(this.DataSourceFileName, FileMode.Open, FileAccess.Read);
if (tmp1 != null)
((IDisposable)tmp1).Dispose();
return true;
// And we can simplify this further by removing the null check since File.Open won't
// return null. See https://msdn.microsoft.com/en-us/library/b9skfh7s%28v=vs.110%29.aspx
// for the documentation.
FileStream tmp1 = File.Open(this.DataSourceFileName, FileMode.Open, FileAccess.Read);
((IDisposable)tmp1).Dispose();
return true;
// The cast is unnecessary since FileStream exposes the Dispose() method. (The cast is
// there because IDisposable could be implemented as an explicit interface, hiding
// the Dispose method on FileStream itself.
FileStream tmp1 = File.Open(this.DataSourceFileName, FileMode.Open, FileAccess.Read);
tmp1.Dispose();
return true;
// Then, we remove the temporary variable, and are left with:
File.Open(this.DataSourceFileName, FileMode.Open, FileAccess.Read).Dispose();
return true;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment