The C# compiler infers generic types from parameters, but there is no parameter of type K
in your method.
As an alternative, you could use the following method:
static class Extensions
{
public static IList<T> Clone<T>(this IList<T> listToClone)
where T : ICloneable
{
var list = (IList<T>)Activator.CreateInstance(listToClone.GetType());
foreach (var item in listToClone)
{
list.Add((T)item.Clone());
}
return list;
}
}
Note that:
- This could fail at runtime (the list type doesn't have a public parameterless constructor - somewhat unlikely)
- You'd still to cast the result to the original type
You might want to consider using serialization as an alternative method for deep-cloning objects.