using
declarations were just introduced in C# 8.0
but they don't behave the same as using
blocks, or so i think.
The following nested using
block works fine:
using (var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream(serviceKey))
using (var file = new FileStream(path, FileMode.Create, FileAccess.Write))
{
resource?.CopyTo(file);
}
But when i convert to a using
declaration as follows, i get an IOException
which says the file is being used by another process:
using var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream(serviceKey);
using var file = new FileStream(path, FileMode.Create, FileAccess.Write);
resource?.CopyTo(file);
I want to understand what's different and how\when to use the new using
declaration?
Both using declaration differ in the way they resolve scope. Old Using used to define its own scope using the curly braces,
using var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream(serviceKey);
using (var file = new FileStream(path, FileMode.Create, FileAccess.Write))
{
resource?.CopyTo(file);
}
Here both resource and file will be disposed the moment the closing braces are found.
With, The new declaration if you haven,t defined a scope like the above, It will automatically attach to the nearest scope,
void certainMethod()
{
using var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream(serviceKey);
using var file = new FileStream(path, FileMode.Create, FileAccess.Write);
resource?.CopyTo(file);
}
Here when the method call to certainMethod
ends, Dispose for resource and file will be called.
Edit: To your case, There shouln't be any issue if your code is doing just this, But if there are two of such blocks, First one will work but second will fail, Example,
void certainMethod()
{
using var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream(serviceKey);
using var file = new FileStream(path, FileMode.Create, FileAccess.Write);
resource?.CopyTo(file);
using var oneMoreFile = new FileStream(path, FileMode.Create, FileAccess.Write);
//This will fail
resource?.CopyTo(oneMoreFile );
}