Code Inspection: Iteration variable can be declared with a more specific type
Consider the following class hierarchy:
public class Person
{
public string Name { get; set; }
}
public class Child : Person
{
}
If we wanted to write a method that would print all of children’s names, we could define the following:
public void Print(IEnumerable<Child> children)
{
foreach (Person p in children)
Console.WriteLine(p.Name);
}
However, why should our iteration variable be Person
? In fact, we could easily change it to Child
and still get the same result. Note that there is a case when a more general type could not be replaced with a derived one without changes to the way code behaves. This case can occur if your iteration variable is declared to be of type dynamic
.
Last modified: 07 April 2022