C # Accessing non-conjugate object methods in an interface array

I have an interface array named iBlocks that contains objects of more than one class (they all implement the iBlocks interface). I am wondering if this is possible, or how else to deal with a situation in which I need to call methods not covered by the interface for all objects of a certain class inside that array. For example:

iBlocks = new iBlocks[1];
iBlocks[0] = new greenBlock();
iBlocks[1] = new yellowBlock();

foreach (greenBlock in iBlocks)
{
   greenBlock.doStuff()
}

      

Where doStuff () is a method not defined in the interface as it is not used in the yellowBlock class. The actual interface works brilliantly as greenBlock and yellowBlock share many features in common. However, there are specific aspects of each class that I would like to access without creating a completely separate array for each type of object. Thanks in advance!

+3


source to share


1 answer


You can use the operator as

.

foreach (var block in iBlocks)
{
    var green = block as greenBlock;
    if (green != null)
         green.doStuff()
}

      



Or in LINQ

foreach (var green in iBlocks.OfType<greenBlock>())
{
    green.doStuff()
}

      

+6


source







All Articles