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.
CodePudding user response:
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:
- an
Item[]
indexer and - a
Count
property (derived fromICollection<T>
).
CodePudding user response:
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