I’m still trying to wrap my head around delegate functions and extension methods. I have created an extension method for DropDownList. I’d like to pass the function to be called in my extension method but I’m getting an error Argument type 'IOrderedEnumerable<KeyValuePair<string,string>>' is not assignable to parameter type 'System.Func<IOrderedEnumerable<KeyValuePair<string,string>>>'
public static class DropDownListExtensions {
public static void populateDropDownList(this DropDownList source, Func<IOrderedEnumerable<KeyValuePair<string, string>>> delegateAction) {
source.DataValueField = "Key";
source.DataTextField = "Value";
source.DataSource = delegateAction;
source.DataBind();
}
}
being called like so…
myDropDownList.populateDropDownList(getDropDownDataSource());
getDropDownDataSource signature…
protected IOrderedEnumerable<KeyValuePair<string,string>> getDropDownDataSource() {
StateInfoXmlDocument stateInfoXmlDocument = new StateInfoXmlDocument();
string schoolTypeXmlPath = string.Format(STATE_AND_SCHOOL_TYPE_XML_PATH, StateOfInterest, SchoolType);
var nodes = new List<XmlNode>(stateInfoXmlDocument.SelectNodes(schoolTypeXmlPath).Cast<XmlNode>());
return nodes.Distinct().Select(x => new KeyValuePair<string, string>(x.Attributes["area"].Value, x.Attributes["area"].Value)).OrderBy(x => x.Key);
}
You should remove the
()aftergetDropDownDataSourcewhen calling:EDIT: Method groups can be implicitly converted to delegates with a compatible signature. In this case
getDropDownDataSourcematches the signature ofFunc<IOrderedEnumerable<KeyValuePair<string,string>>>so the compiler applies the conversion for you, effectively doing