The problem of the code sample in question is that interface method is not exposed to the class user.
There are two forms:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CritterInterfaces;
namespace CritterWorld
{
public class CritterFactoryGood : ICritterFactory
{
ICritterBrain[] someArray = new ICritterBrain[2];
ICritterBrain[] ICritterFactory.CreateCritterBrains()
{
return someArray;
}
}
public class CritterFactoryQuestionable : ICritterFactory
{
ICritterBrain[] someArray = new ICritterBrain[2];
public ICritterBrain[] CreateCritterBrains()
{
return someArray;
}
}
}
First form as in
CritterFactoryGood
is better because it is safer, does not create redundant access and encourage separation of interface and class references or structures. Consider this:
ICritterFactory ifactory = new CritterFactoryGood();
var result1 = ifactory.CreateCritterBrains();
CritterFactoryGood factoryInstance = new CritterFactoryGood();
var result2 = factoryInstance.CreateCritterBrains();
With
CritterFactoryQuestionable
, both variants would compile. Also, with first form, a class can have two properties methods with identical signature and names implementing two different interfaces, importantly, two indexed "this" properties.
—SA