Identify Interface in ArrayList of Intfaces

  • Thread starter Thread starter Sam
  • Start date Start date
S

Sam

Hi

I am trying to create a arraylist of Intefaces so I only need to create each
once and I would like to
be able to identify the specific interface when I loop thru ???

Is there some way to set a Custom Attribute on each Instance of the
Interface???

Thanks


public interface IAnimal
{
bool Print();
}

public class Dog : IAnimal
{
public bool Print()
{
Console.WriteLine("Dog");
return true;
}
}

public class Cat : IAnimal
{
public bool Print()
{
Console.WriteLine("Cat");
return true;
}
}



public class PROGRAM
{
static public void Main()
{

ArrayList myArrList = new ArrayList();
myArrList.Add(new Dog());
myArrList.Add(new Cat());

foreach (IAnimal thing in myArrList)
{
//How to tell What IAminal is???
}

}

}
 
foreach (IAnimal thing in myArrList)
{
//How to tell What IAminal is???
}

You can use the is operator to check if an object is of a certain
type.

if (thing is Dog) ...

But isn't the whole point of using the IAnimal interface that you
shouldn't have to care what kind of animal it is?


Mattias
 
You are correct but at some point you need to pick an interface depending
on incoming data

if (dog data)
myAnimal = new (dog)
if(cat data)
myAnimal = new(cat)

......

for (int i =0; i<1000000; i++)
{
if (dog data)
myAnimal = new (dog)
if(cat data)
myAnimal = new(cat)

......

}

if I have to do this in a loop a million times and I have some significant
i/o needed on the constructors
then i was thinking of holding onto the interface - I guess when I do "new"
I can add to a hastable with
a type as the key instead of an arraylist and try to find type

Thanks
 
You are correct but at some point you need to pick an interface
depending on incoming data

if (dog data)
myAnimal = new (dog)
if(cat data)
myAnimal = new(cat)

Unless you need to do specific processing of cats and dogs in this code,
myAnimal can be of type IAnimal.
.....

for (int i =0; i<1000000; i++)
{
if (dog data)
myAnimal = new (dog)
if(cat data)
myAnimal = new(cat)
.....

}

if I have to do this in a loop a million times and I have some
significant
i/o needed on the constructors
then i was thinking of holding onto the interface - I guess when I do
"new"
I can add to a hastable with
a type as the key instead of an arraylist and try to find type

What interface would you like to hold on to and why? Before you construct
the object you don't have an interface to it and if you only need to handle
it as an IAnimal afterwards then you don't need to know which specific one
you have.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top