3 ms·
I find in C# you use it without thinking about it because it usually makes sense when you have specific things you are trying to do, you often don't think too m
by keithnz 8y ago
I find in C# you use it without thinking about it because it usually makes sense when you have specific things you are trying to do, you often don't think too much about the types.
public interface ITalker
{
string Talk();
}
public class Robot : ITalker
{
public string Talk() => "Beep Boop";
}
class Program
{
static void Main(string[] args)
{
var robots = new List<Robot>() {new Robot()};
MakeEmTalk(robots);
DoStuffWithRobots(MakeEmTalk, robots);
}
private static void DoStuffWithRobots(Action<List<Robot>> robotoStuff, List<Robot> robots)
{
robotoStuff(robots);
}
private static void MakeEmTalk(IEnumerable<ITalker> talkers)
{
foreach (var talker in talkers)
{
Console.WriteLine(talker.Talk());
}
}
}
so intuitively, with MakeEmTalk, a list of robots should be able to be used where a enumerable list of talkers is required.
conversely ( contraversely? ) with DoStuffWithRobots, an action on a list of robots should be able to use a more generic action that works on an enumerable of Italkers, while we are only dealing with a list of robots there shouldn't be anything that stops us using something designed to work on a broader set of things.