I have a base class called SCO that a number of classes inherit from. I initially just wanted to sort the collection, but based off of some recommendations, it sounds like I can instantiate and sort the collection in one method.
I have this constructor that all base classes inherit:
public SCO(SPListItem item, List<Vote> votes)
{
UpVotes = voteMeta.UpVotes;
DownVotes = voteMeta.DownVotes;
VoteTotal = UpVotes - DownVotes;
HotScore = Calculation.HotScore(Convert.ToInt32(UpVotes), Convert.ToInt32(DownVotes), Convert.ToDateTime(item["Created"]));
}
This is where I get stuck. I cannot instantiate <T>.
public static List<T> SortedCollection<T>(SPListItemCollection items, ListSortType sortType, List<Vote> votes) where T : SCO
{
var returnlist = new List<T>();
for (int i = 0; i < items.Count; i++) { returnlist.Add(new T(items[i], votes)); }
switch (sortType)
{
// Sort List based on passed ENUM
}
return returnlist;
}
If I can do all of this in one method, I avoid some costly casting AND boxing.
The only constraint allowable in generics is
new(), which will only work if there is a constructor which does not take any parameters.The problem is that this isn’t enforceable. Sub classes are (and should be) free to define their own constructors, as long as they chain to this constructor. A sub class is free to use whatever construction mechanism required to instantiate that class.
You could work around this via reflection and Activator.CreateInstance, which will allow you to construct the object with parameters. However, this is fairly “ugly” (though, not that ugly considering that using the new() constraint still calls Activator.CreateInstance):