I found this question: Is it possible to specify a generic constraint for a type parameter to be convertible FROM another type? I am looking for a smarter way.
Class A {
public A(string){}
}
Class foo
{
private List<A> content = new List<A>();
public void Add(A a){
content.Add(a);
}
public void Add(string str){
content.Add(new A(str));
}
public void AddRange<T>(IEnumerable<T> iterable) // where T : ???
{
foreach(T t in iterable)
content.Add((A)t); //Error
}
}
The Error is:
Cannot convert type 'T' to 'A'
Question: Exists a where T : ?
expression like "convertable"?
Update:
I have two method overloadings:
Add(A)
and Add(string)
Currently i try to convert T to A. But my main problem is, that i want to use different Add
methods relating to T.
What i need is something like:
public void AddRange<T>(IEnumerable<T> iterable) where T : Add(T)
{
foreach (T t in iterable)
this.Add(t);
}