I was trying to write a piece of code for converting a list of strings to a list of ints
I got the List<int> list = listOfStr.ConvertAll<int>(delegate(string s) { return ConvertStringToInt(s); }); line from ConvertAll .
public static List<int> ConvertListOfStringToListOfInt(List<string> listOfStr)
{
List<int> list = listOfStr.ConvertAll<int>(delegate(string s) { return ConvertStringToInt(s); });
return list;
}
/// <summary>
/// converts the given str to integer
/// </summary>
/// <param name="str">string to be converted</param>
/// <returns>returns the int value of the given string</returns>
public static int ConvertStringToInt(string str)
{
int convertedValue = int.Parse(str);
//(int.TryParse(str, out convertedValue))
return convertedValue;
}
The code is working fine except one thing.
I created Unit Test for the above method, the TestMethod is below
/// <summary>
///A test for ConvertListOfStringToListOfInt
///</summary>
[TestMethod()]
public void ConvertListOfStringToListOfIntTest()
{
List<string> listOfStr = new List<string> { "1", "2", "3"}; // TODO: Initialize to an appropriate value
List<int> expected = new List<int> { 1, 2, 3}; // TODO: Initialize to an appropriate value
List<int> actual;
actual = Conversions.ConvertListOfStringToListOfInt(listOfStr);
Assert.AreEqual(expected, actual);
//Assert.Inconclusive("Verify the correctness of this test method.");
}
I have given the same values into the list I pass the method and expected list, just different by type(expected is a list of integer and passed list is a list of strings). I run the test and got this Error Message:
Assert.AreEqual failed. Expected:<System.Collections.Generic.List`1[System.Int32]>. Actual:<System.Collections.Generic.List`1[System.Int32]>.
Well, the types are actually equal so I thought there might be something different inside the lists and I debugged it.
It turned out listOfStr.Capacity is 4 and has null item as the [3] item in it's items member, for same place in items member expected has a 0 and expected.Capacity is 4,too.
However, actual.Capacity is 3 and it actually does have 3 items in it's items member.
I tried to newing actual before filling it and using list.Add() for adding values to expected and newing list in the ConvertListOfStringToListOfInt method. But the capacities are still the same. I do not want to set the capacity manually because this method will not be used for lists which has determined capaties.
What can I do to pass this test? Why is the capacities different? And how is the capacity of lists are determined, what do they depend on?
This is .NET Framework 4.0.