C Sharp Pointer to a Function


Here is one implementation of a Pointer to a Function:
To e-mail a suggestion or comment: sam@gilcrist.com

Creating a variable set of functions - Also known as pointers to functions

I have found that there have been several occasions where I did not know what functions would be called nor in which order. This situation can be very neatly resolved using pointers to function.

The following example is very simple. It presumes there is a form that has a button called btnFuncTest and a textbox called txtFunctionName. List lFuncs is a list of delegates of type CallFunc that can be added to dynamically.

If the user types in "test" a delegate (or pointer) to the function "test" is loaded for later use. If the user types "testTwice" the same function is loaded twice. A really dumb example, except it makes the point.

f() actually calls the function, and the function runs and returns 0.



	//the pointer
        public delegate int CallFunc();

	//the function
	private int test()
        {
            return 0;
        }

        private void btnFuncTest_Click(object sender, EventArgs e)
        {

            int nRetVal = 0;
	    //a container to hold the delegates (pointers to functions)
            List<CallFunc> lFuncs = new List<CallFunc>();

	    //load delegates into the list
            switch (txtFunctionName.Text.ToLower())
            {
                case "test":
                    lFuncs.Add(new CallFunc(test));
                    break;
		case "testtwice":
                    lFuncs.Add(new CallFunc(test));
		    lFuncs.Add(new CallFunc(test));
                    break;

            }

            if (lFuncs.Count > 0)
            {
		//pop delegates out of the list
                foreach (CallFunc f in lFuncs)
                {
		    //call the function
                    nRetVal = f();
                }
            }

        }