You can definitely still read from the variable. There's no problem in terms of definite assignment, or you'd get a compile-time error. For example, this is fine:
using System;
using System.IO;
class Test
{
static void Main()
{
string x;
using (new MemoryStream())
{
x = "hello";
}
Console.WriteLine(x);
}
}
That's absolutely fine.
Now if SevenZipArchive returns a ReadOnlyCollection<string>, I'd usually expect that to still be valid after the archive itself is disposed. However, ReadOnlyCollection<T> is simply a wrapper around another collection... and if that collection is being invalidated by disposing of archive, that would certainly explain things.
Unfortunately, Joel's suggested way of copying the collection is only creating another wrapper - which will ask the first wrapper for the count, in turn asking the original (invalidated) collection.
Here's one approach which should work:
private ReadOnlyCollection<string> ExtractRar(string varRarFileName,
string varDestinationDirectory) {
ReadOnlyCollection<string> collection;
using (var archive = new SevenZipArchive(varRarFileName)) {
collection = new ReadOnlyCollection<string>(archive.Volumes.ToList());
MessageBox.Show(collection.Count.ToString()); // output 10
}
MessageBox.Show(collection.Count.ToString()); // output 0
return collection;
}
Note the extra call to ToList(). That will force the collection to be copied to a List<string> first... truly copied, not just creating a wrapper.
Of course, if you don't really mind if the method returns a List, you could just use:
private List<string> ExtractRar(string varRarFileName,
string varDestinationDirectory) {
List<string> collection;
using (var archive = new SevenZipArchive(varRarFileName)) {
collection = archive.Volumes.ToList();
MessageBox.Show(collection.Count.ToString()); // output 10
}
MessageBox.Show(collection.Count.ToString()); // output 0
return collection;
}
... and then when you don't need the extra diagnostics:
private List<string> ExtractRar(string varRarFileName,
string varDestinationDirectory) {
using (var archive = new SevenZipArchive(varRarFileName)) {
return archive.Volumes.ToList();
}
}
(I'm assuming you're using .NET 3.5 or higher, by the way, to use the ToList extension method.)