Assuming I have the following delegate
public delegate void ControlInitializer(Control control);
Is there a way when specifying the delegate to specify what type of control the input parameter is? e.g.
Instead of
ControlInitializer one = c => ((TextBox)c).Text = "Init Value"
ControlInitializer two = c => ((DropDownList)c).SelectedValue= "-1"
Can I do something like
ControlInitializer one = (TextBox c) => c.Text = "Init Value"
ControlInitializer two = (DropDownList c) => c.SelectedValue= "-1"
As Textbox is a sub class of Control in this case?
Update: I also need to store these 2 ControlInitialiser delegates in a e.g.
Dictionary<string, ControlInitializer>
will specifying
Dictionary<string, ControlInitializer<Control>>
Work in this case as I can’t seem to get it to work.
Thanks in advance.
You can make the delegate generic:
And then use it like this:
I guess your aiming for something like this:
That’s a bit difficult due to the reasons mentioned in David B‘s answer. What you can do, however, is hide the type cast behind an abstraction, like this: