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:
.
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:
.
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.
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: