My code is as follows:
class PropertyRetrievalClass
{
public delegate object getProperty(string input);
public object get_Chart_1(string iput)
{
Console.WriteLine(iput);
return "";
}
public object get_Chart_2(string iput)
{
Console.WriteLine(iput);
return "";
}
public PropertyRetrievalClass() { }
}
public static void Main()
{
int i = 1;
PropertyRetrievalClass obj = new PropertyRetrievalClass();
Delegate del = Delegate.CreateDelegate(typeof(PropertyRetrievalClass), obj, "get_chart_" + i.ToString());
string output= del("asldkl");
}
It is giving me an error saying “error CS0118: ‘del’ is a ‘variable’ but is used like a ‘method'”
What should I do to use this delegate? I want to call any of “get_chart_1” or “get_chart_2” function and both of them take a string input?
Thanks in advance…
You have two issues in your code.
Delegateobject is not a method, so you need to use a method on theDelegateobject to invoke the method it refersCreateDelegateshould be the delegate type, not the class containing a method you want to invoke.Full working example:
In your case, the
Mainmethod should look like this:Update
Note that
CreateDelegateis case sensitive on the method name, unless you tell it not to.