Finding type of objects in a collection

  • Thread starter Thread starter John Spiegel
  • Start date Start date
J

John Spiegel

Hi all,

I'm trying to create a subclass of an ArrayList that is intended
specifically for holding FileInfo objects. My idea to restrict this is to
override the Add and AddRange methods to allow only FileInfo objects. In
AddRange, how can I verify that the collection passed is a collection of
FileInfo objects?

TIA,

John
 
It is generally recommended to derive from CollectionBase instead of
ArrayList for your custom collections. Check out this article for some
hints:
http://www.c-sharpcorner.com/Code/2002/Aug/StrongTypedCollections.asp

You can then create your own AddRange method that only accepts a
FileInfo array:

public void AddRange(FileInfo[] files)

If you want to stick with overriding the ArrayList, I don't think there
is anything you can do aside from looping over the collection and
checking the type of each object in the collection. It probably won't
be the most performant code, and you probalby lose the performance
benefit of the AddRange method.

public override void AddRange(System.Collections.ICollection c) {
foreach(object item in c){
if (!item is System.IO.FileInfo) {
throw new ArgumentException("");
}
base.AddRange(c);
}

Instead of throwing an exception if one item is bad, you could just
ignore the objects that are not FileInfos, and call base.Add(item) for
the ones that are.

Joshua Flanagan
http://flimflan.com/blog
 
Thanks, Joshua. Will look at that CollectionBase idea!

- John
Joshua Flanagan said:
It is generally recommended to derive from CollectionBase instead of
ArrayList for your custom collections. Check out this article for some
hints:
http://www.c-sharpcorner.com/Code/2002/Aug/StrongTypedCollections.asp

You can then create your own AddRange method that only accepts a FileInfo
array:

public void AddRange(FileInfo[] files)

If you want to stick with overriding the ArrayList, I don't think there is
anything you can do aside from looping over the collection and checking
the type of each object in the collection. It probably won't be the most
performant code, and you probalby lose the performance benefit of the
AddRange method.

public override void AddRange(System.Collections.ICollection c) {
foreach(object item in c){
if (!item is System.IO.FileInfo) {
throw new ArgumentException("");
}
base.AddRange(c);
}

Instead of throwing an exception if one item is bad, you could just ignore
the objects that are not FileInfos, and call base.Add(item) for the ones
that are.

Joshua Flanagan
http://flimflan.com/blog


John said:
Hi all,

I'm trying to create a subclass of an ArrayList that is intended
specifically for holding FileInfo objects. My idea to restrict this is
to override the Add and AddRange methods to allow only FileInfo objects.
In AddRange, how can I verify that the collection passed is a collection
of FileInfo objects?

TIA,

John
 
Back
Top