Is is possible in C# to have the equivalent of an array of function pointers in C?
I have a situation where a top level class exposes methods like Add, Delete, ... and a few
child classes with the same methods. Depending on a configuration parameter, the child
method will be invoked when the top level class is invoked.
I would like to avoid having to do something like this:
int configuration;
public bool Add()
{
switch (configuration)
{
case 1:
return ChildClass1.Add ();
case 2:
return ChildClass2.Add ();
}
}
I would rather have something like this instead (code not complete)
Arraylist MethodPTR;
int configuration;
public mainClassConstr uctor()
{
// Initialize MethodPTR with the address of the methods
MethodPTR = new ArrayList(8);
configuration = RetrieveConfigu ration();
switch (configuration)
{
case 1:
MethodPTR[0] = ChildClass1.Add ; // Assistance required here
MethodPTR[1] = ChildClass1.Del ete; // Assistance required here
break;
case 2:
MethodPTR[0] = ChildClass2.Add ; // Assistance required here
MethodPTR[1] = ChildClass2.Del ete; // Assistance required here
break;
}
}
public bool Add()
{
return MedthoPTR[0](); // This is where I need assistance
}
public bool Delete()
{
return MedthoPTR[1](); // This is where I need assistance
}
Thank you all in advance.
Gaetan
I have a situation where a top level class exposes methods like Add, Delete, ... and a few
child classes with the same methods. Depending on a configuration parameter, the child
method will be invoked when the top level class is invoked.
I would like to avoid having to do something like this:
int configuration;
public bool Add()
{
switch (configuration)
{
case 1:
return ChildClass1.Add ();
case 2:
return ChildClass2.Add ();
}
}
I would rather have something like this instead (code not complete)
Arraylist MethodPTR;
int configuration;
public mainClassConstr uctor()
{
// Initialize MethodPTR with the address of the methods
MethodPTR = new ArrayList(8);
configuration = RetrieveConfigu ration();
switch (configuration)
{
case 1:
MethodPTR[0] = ChildClass1.Add ; // Assistance required here
MethodPTR[1] = ChildClass1.Del ete; // Assistance required here
break;
case 2:
MethodPTR[0] = ChildClass2.Add ; // Assistance required here
MethodPTR[1] = ChildClass2.Del ete; // Assistance required here
break;
}
}
public bool Add()
{
return MedthoPTR[0](); // This is where I need assistance
}
public bool Delete()
{
return MedthoPTR[1](); // This is where I need assistance
}
Thank you all in advance.
Gaetan
Comment