I want to create a wrapper function for a generic class like so:
public class ColumnData
{
public static ColumnData<T> Create<T>(string name, int width, ColumnType type,
Func<T, string> dataFormater)
{
return new ColumnData<T>(name, width, type, dataFormater);
}
}
The Create method will be called as an argument to another function with a signature:
public void populateFromData<TDATA>(IEnumerable<TDATA> data,
params ColumnData<TDATA>[] columns)
{
...
}
The intent here is to be able to do:
var myData = new List<MyDataType>();
dataListView.populateFromData(
myData,
ColumnData.Create("ID", 40, ColumnType.Numeric, x => x.ID.ToString());
However, Create can’t infer the correct type for itself based on the signature it’s expected to have, and thus the lambda doesn’t know itself either.
Is this a limitation of type inference, or is there a way to make this setup work?
Note: I’m willing to specify the actual data type somewhere in this function call, if necessary, but I don’t want to specify it for each .Create().
As others have explained, it’s not possible with the exact syntax you want. As a workaround, you could possibly move the typing to a separate building class:
Then usage might look like:
Or closer to your example usage (if you want to keep
populateFromDataon yourdataListView) in which case you can ditch theColumnDataBuilder<T>.populateFromDatamethod (since it seems from your comments that’s not possible to keep there):Or a bit of best of both worlds:
EDIT: Considering your comments, you probably don’t want
populateFromDataor possibly even theIEnumerable<T> Datastored on theColumnDataBuilder, so you might simplify to have this instead:With the usage from above: