user2056413
user2056413

Reputation: 33

C# Accessing non-interfaced methods of an object in an interface array

I have an Array of an interface named iBlocks which contains objects of more than a single class(that all implement the iBlocks interface). I'm wondering if it is possible, or how else to handle the situation in which i need to call methods not covered by the interface for all objects of a certain class within this 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 has no use in the yellowBlock class. The actual interface works brilliantly as greenBlock and yellowBlock have tons of common features. However, there are special aspects of each class i would like to still access without creating an entirely separate array for each object type. Thanks in advance!

Upvotes: 3

Views: 84

Answers (1)

Richard Schneider
Richard Schneider

Reputation: 35464

You can use the as operator.

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()
}

Upvotes: 6

Related Questions