Well, first some comments than an answer to your questions.
1) Not really sure if your desired way is any better than the way you are
rejecting. You are still using a switch statement, you are just moving it
to a new location.
2) People who work on this after you may not understand what you are doing.
You would need to document this really well.
3) Although not a big issue, your way would not be as performant because
you are storing pointers to the methods. There would also be the overhead
of calling the methods. (again this is not a big deal, just thought I would
mention it.)
Now, for your answer. The .NET equivalent of function pointers are
Delegates. When you create a delegate, you tell it what method it should
wrap. You can then store the delegate for later use.
On a side note, let me offer some design comments (knowing full well that I
do not have knowledge of what you are trying to accomplish).
When you say "child class", are you referring to inherited subclasses? If
that is the case, then you might want to make Add abstract and then the
correct derived class method will be called, or you can have the base class
have an Add method and the derived classes have an AddImpl method incase you
need the base class to do some additional work. I might be able to offer a
better design if you wanted to share the relationship between the various
classes (i.e. inheritance, composition, etc.).
"Gaetan" <so*****@somewhere.com> wrote in message
news:jo********************************@4ax.com...
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 mainClassConstructor()
{
// Initialize MethodPTR with the address of the methods
MethodPTR = new ArrayList(8);
configuration = RetrieveConfiguration();
switch (configuration)
{
case 1:
MethodPTR[0] = ChildClass1.Add; // Assistance required here
MethodPTR[1] = ChildClass1.Delete; // Assistance required here
break;
case 2:
MethodPTR[0] = ChildClass2.Add; // Assistance required here
MethodPTR[1] = ChildClass2.Delete; // 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