Reputation: 3057
I am using IEnumerable
in a for each loop as follows:
foreach (IListBlobItem blobItem in container.ListBlobs())
{
if (blobItem is CloudBlobDirectory)
{
CloudBlobDirectory directory = (CloudBlobDirectory)blobItem;
IEnumerable<IListBlobItem> blobs = directory.ListBlobs(true);
}
}
await ProcessBlobs(blobs);
I would like to use blobs
variable outside of this foreach loop but I get this message: blobs doesnot exist in the current context
I decided to define blobs
outside of the foreach loop:
IEnumerable<IListBlobItem> blobs = new IEnumerable<IListBlobItem>;
foreach (IListBlobItem blobItem in container.ListBlobs())
{
if (blobItem is CloudBlobDirectory)
{
//Console.WriteLine(blobItem.Uri);
CloudBlobDirectory directory = (CloudBlobDirectory)blobItem;
IEnumerable<IListBlobItem> blobs = directory.ListBlobs(true);
}
}
but I get the error: can not create an instance of the abstract class or interface IEnumerable<IListBlobItem>
Do you have any idea how can I solve this problem?
Upvotes: 1
Views: 524
Reputation: 688
You are trying to create an object of an interface which is impossible. Instead, declare blobs
as object an then convert it to IEnumerable<IListBlobItem>
.
object blobs = null;
foreach (IListBlobItem blobItem in container.ListBlobs())
{
if (blobItem is CloudBlobDirectory)
{
//Console.WriteLine(blobItem.Uri);
CloudBlobDirectory directory = (CloudBlobDirectory)blobItem;
blobs = directory.ListBlobs(true);
}
}
///usage:
///(IEnumerable<IListBlobItem>)blobs
Also, you can declare blobs as IEnumerable<IListBlobItem>
which other answers cover.
Upvotes: 2
Reputation: 6977
Use default
to get default value. This will return null for reference type
IEnumerable<IListBlobItem> blobs = default(IEnumerable<IListBlobItem>);
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/default
Upvotes: 1
Reputation: 399
Set IEnumerable blobs like property in this way:
IEnumerable<IListBlobItem> blobs{get;set;}
Upvotes: 1
Reputation: 4379
Try using Enumerable.Empty<TResult>
, like so:
IEnumerable<IListBlobItem> blobs = Enumerable.Empty<IListBlobItem>();
This will return an empty, non-null enumerable.
Upvotes: 2
Reputation: 186833
You can declare blobs
being an empty collection, say, array:
// Empty
IEnumerable<IListBlobItem> blobs = new IListBlobItem[0];
foreach (IListBlobItem blobItem in container.ListBlobs())
{
if (blobItem is CloudBlobDirectory)
{
CloudBlobDirectory directory = (CloudBlobDirectory)blobItem;
blobs = directory.ListBlobs(true);
}
}
// process either blobs from foreach or an empty collection
await ProcessBlobs(blobs);
Upvotes: 2