I have the following (working) code:
List<string> stringList = new List<string> { "foo", "bar" };
var ret = stringList.ConvertAll(item => (MyString)item);
This works well since I provided an explicit cast operator:
public struct MyString
{
private readonly string _myString;
public MyString(string myString)
{
_myString = myString;
}
[...]
public static explicit operator MyString(string myString)
{
return new MyString(myString);
}
}
Now my issue is that I cannot express this as constraints in the following code:
public List<T> conv<T>(List<string> stringList)
{
var ret = stringList.ConvertAll(item => (T)item); // <-- CS0030: Cannot convert type 'string' to 'T'
return ret;
}
What where
constraint incantation am I missing here ?
Update:
I specifically used ConvertAll
based on the following SO post:
As a side note, I get the exact same error using:
public List<T> conv<T>(List<string> stringList)
{
var ret = stringList.Select(x => (T)x).ToList();
return ret;
}