Below is a heavily cut down version of some code I have
public class DataInfo<T>
{
public DataInfo(string description, Func<T, object> funcToGetValue)
{
this.description = description;
this.funcToGetValue= funcToGetValue;
}
public readonly string description;
public readonly Func<T, object> funcToGetValue;
}
public class DataType1
{
public int fieldA { get; set; }
public string fieldB { get; set; }
}
public class CurrentUse
{
static List<DataInfo<DataType1>> data1 = new List<DataInfo<DataType1>>()
{
new DataInfo<DataType1>("someStuff", data => data.fieldA),
new DataInfo<DataType1>("someOtherStuff", data => data.fieldB)
};
}
(There are many types, and don't worry not everything is public really!)
This is working and is OK as far as it goes, but the fact that I have to keep repeating new DataInfo<DataType1>
bothers me a bit.
I tried creating a non generic helper verion of DataInfo to create the objects for me as so
public class DataInfo
{
public static DataInfo<T> Create<T>(string description, Func<T, object> func)
{
return new DataInfo<T>(description, func);
}
}
public class DesiredUse
{
static List<DataInfo<DataType1>> data1 = new List<DataInfo<DataType1>>()
{
DataInfo.Create("someStuff", data => data.fieldA),
DataInfo.Create("someOtherStuff", data => data.fieldB)
};
}
But that doesn't work as it the compiler cannot resolve fieldA & fieldB as it cannot infer the type of data.
Any ideas how I can get rid of the duplicated type info? I don't mind making changes, as long as I end up with a list of DataInfos