Reputation: 589
Trying to write my first generic class in C#:
public class HighScoreList<ScoreType>
where ScoreType : System.IComparable<ScoreType>
{
...
public HighScoreList(List<ScoreType> highScoreList)
{
....
}
...
}
I have run into problems writing unit tests for it. It can't for some reason match the constructor's argument list and gives me the error:
Error 7 The best overloaded method match for 'TDGLX.FileManagement.HighScoreList.HighScoreList(System.Collections.Generic.List)' has some invalid arguments C:\Users\eric\Documents\Visual Studio 2010\Projects\TDGLX\UnitTests\FileManagmentTest\HighScoreListTest.cs 183 54 UnitTests
On this and several other tests:
HighScoreList<GenericScore> highScoreList =
new HighScoreList<GenericScore>(new List<GenericScore>()
{
new GenericScore("Person1",400),
new GenericScore("Person2",200),
new GenericScore("Person3",100)
});
HighScoreList<GenericScore> target =
new HighScoreList<GenericScore>(highScoreList);
Here is the class that I'm using as a parameter to the template argument list in my tests.
[Serializable()]
public class GenericScore : System.IComparable<GenericScore>
{
public GenericScore(string name,int score)
{
Name = name;
Score = score;
}
public string Name { get; set; }
public int Score { get; set; }
public int CompareTo(GenericScore other)
{
return this.Score.CompareTo(other.Score);
}
}
I really can't figure out what's wrong with the test. Is there something have misunderstood about C# generics?
Upvotes: 2
Views: 289
Reputation: 46098
On your second call to the HighScoreList
ctor, you're passing in an instance of HighScoreList<GenericScore>
as the List<GenericStore>
ctor argument, but HighScoreList<T>
doesn't inherit off List<T>
, hence the error.
As a point of style, generic type names usually start with T, so it'll be HighScoreList<TScoreType>
, or just HighScoreList<T>
Upvotes: 3
Reputation: 292415
HighScoreList<GenericScore> target =
new HighScoreList<GenericScore>(highScoreList);
In the code above, you're passing a HighScoreList<GenericScore>
to the constructor of HighScoreList<GenericScore>
, but it expects a List<GenericScore>
Isn't that what you want ?
List<GenericScore> highScoreList = new List<GenericScore>()
{
new GenericScore("Person1",400),
new GenericScore("Person2",200),
new GenericScore("Person3",100)
};
HighScoreList<GenericScore> target =
new HighScoreList<GenericScore>(highScoreList);
Upvotes: 6