Reputation: 109
I have two methods that perform the same task: one receiving an array parameter and the a List parameter, both of type string.
Is there a way to replace these two methods by a single method? What type of parameter can replace both?
The methods are:
public static void NumberLinesInCollection(List<string> list, int startNumberingFromRowNumber = 0)
{
int numberOfLines = list.Count;
for (int i = startNumberingFromRowNumber; i < numberOfLines; i++)
{
string sourceString = (i + 1).ToString();
string resultingString = StringOperations.PadWithBlanks(originalString: (i + 1).ToString(),
fieldLength: numberOfLines.ToString().Length,
position: PaddingDirection.left);
list[i] = resultingString + ". " + list[i];
}
}
and
public static void NumberLinesInCollection(string[] arrayOfStrings, int startNumberingFromRowNumber = 0)
{
int numberOfLines = arrayOfStrings.Length;
for (int i = startNumberingFromRowNumber; i < numberOfLines; i++)
{
string resultingString = StringOperations.PadWithBlanks(originalString: (i + 1).ToString(),
fieldLength: numberOfLines.ToString().Length,
position: PaddingDirection.left);
arrayOfStrings[i] = resultingString + ". " + arrayOfStrings[i];
}
}
Thank you in advance.
Upvotes: 2
Views: 90
Reputation: 3505
You can use IEnumerable
, then it can be either list
and array
:
public static void NumberLinesInCollection(IEnumerable<string> list, int startNumberingFromRowNumber = 0)
{
}
Upvotes: 1
Reputation: 172478
From the documentation of System.Array:
Single-dimensional arrays implement the
IList<T>
,ICollection<T>
,IEnumerable<T>
,IReadOnlyList<T>
andIReadOnlyCollection<T>
generic interfaces. The implementations are provided to arrays at run time, and as a result, the generic interfaces do not appear in the declaration syntax for the Array class.
From the documentation of List<T>
:
Implements
ICollection<T>
,IEnumerable<T>
,IList<T>
,IReadOnlyCollection<T>
,IReadOnlyList<T>
, [and a few non-generic interfaces]
As we can see, there is a nice overlap, allowing you to choose the most fitting interface based on the actual array/list features you require.
In your particular case, IList<T>
seems to be most suitable, since it provides both of the following features used in your code:
Item[]
indexer andCount
property (inherited from ICollection<T>
).Upvotes: 4
Reputation: 1
you can use IList<string>
, this will allow you to pass both List and Array as the parameter while calling the NumberLinesInCollection
. array and list both implement IList
Upvotes: 1