How to choose function implementation at runtime?

MyForumID

Active member
Joined
Sep 25, 2005
Messages
26
Programming Experience
Beginner
How to choose function implementation at runtime? [RESOLVED]

I don't know if this is complicated or not, but I've spent a lot of time trying to understand if this is possible or not and I'm stuck.

What I want to do is very simple in concept - I want to have 2 functions with the same arguments but I want to choose which function to run based on a user defined value and use the same name throughout the code.

For example, let's say we wanted to determine the probability of drawing a red ball out of an urn 2 times. The user has the option to do the calculation with or without replacement. So we'd have the two functions:

VB.NET:
public function TwoRedBallsWithReplacement(byVal nRed as integer, byVal nBalls as integer) as double
    if nBalls>0 then
        return (nRed/nBalls)*(nRed/nBalls)
    else
        return 0
    end if
end function
 
public function TwoRedBallsWithoutReplacement(byVal nRed as integer, byVal nBalls as integer) as double
    if nBalls>1 and nRed>1 then
        return (nRed/nBalls)*((nRed-1)/(nBalls-1))
    else
        return 0
    end if
end function
.
Now if we had a boolean value withReplacement that I got from a checkbox or something, and throughout the code I always wanted to use a general function called TwoRedBalls, the goal I am trying to accomplish is the following:

VB.NET:
if withReplacement then
   TwoRedBalls = TwoRedBallsWithReplacement
else
   TwoRedBalls = TwoRedBallsWithoutReplacement
end if
.
Then later whenever I called TwoRedBalls(x, y) it would give the right answer depending on what the user asked for in the beginning.

I tried reading about interfaces, delegates and function pointers and I haven't found any concrete enough examples to tell if I'm on the right track. I find all the descriptions very confusing.

Thank you very much for any help.
 
Last edited:
well you could have 1 function that will give you the correct answer
and within this 1 function you can check to see which of the two actual functions need to be called

you can call other functions from within a function
 
Thank you for the replies.

The problem with having 1 function is that it requires an if/then or something similar. My primary goal is speed as these functions will be called thousands of times, so if TwoRedBalls is already pointing at the right function then it saves the logical check.

As I've said I've tried reading about delegates but find them very confusing and couldn't find a clear example that would cover the situation above. If you could please give me an example code on how to handle the situation described, I would greatly appreciate it.

Thanks again.
 
Back
Top