I have a project in school where my teacher is asking us to add a delegate to a List of Funcs. The code I have below is having issues in the AddDel method. Intellisense is telling me that it can't convert from the Delegate into a Func but my teacher insists that it should totally do that without a problem. What am I doing wrong?
public class TestDelegate
{
private delegate string MyDel(int iVal, double dVal, char cVal, string sVal);
private List<Func<int, double, char, string, string>> _DList;
public TestDelegate() { }
public void AddDel()
{
//Creating a delegate
MyDel myDel = new MyDel(MyFunction);
_DList.Add(myDel); //Adding it to the TestDelegate
}
public void RunTests()
{
int idata = 1;
double ddata = 5.1;
char cdata = 'A';
string sdata = "Method";
foreach (Func<int, double, char, string, string> myDel in _DList)
WriteLine(myDel(idata, ddata++, cdata++, sdata + idata++));
}
private static string MyFunction(int iVal, double dVal, char cVal, string sVal)
{
return $"{sVal}:\t{iVal} {dVal}{cVal}";
}
}
Basically, you shouldn't declare your own delegate here at all. There are no conversions between delegate types like this.
You want a Func<int, double, char, string, string>
, so declare one:
Func<int, double, char, string, string> func = MyFunction;
_DList.Add(func);
Or more simply, just call Add:
_DList.Add(MyFunction);
If you really want to keep your current code, you can create a Func<...>
that wraps your delegate:
MyDel myDel = new MyDel(MyFunction);
var func = new Func<int, double, char, string, string>(myDel);
_DList.Add(func); //Adding it to the TestDelegate
... but I don't actually see any benefit from that here.
See more on this question at Stackoverflow