Arrays of Functions?

rifter1818

Well-known member
Joined
Sep 11, 2003
Messages
255
Location
A cold dark place
Heres an odd situation ive got myself into, i want to create an array of what i would in C++ call function pointers,.. in a C# application...

pretty much what i would like to create is a situation like this
C#:
(void(Object,EventArgs))[] FPs = {fcNEW,fcLOAD,fcEDIT,fcWHATEVER...};
void fcNEW(Object Sender,EventArgs e){...}
void fcLOAD(Object Sender,EventArgs e){...}
//and so on
if my choice of (void(Object,EventArgs)) didnt give it away i am using these as functions that will be used to handle events, click events on buttons in this case allthought that is errelevant. There are other ways of doing this, but this one seems intreaging enough to ask whether it can be done or not, also can you have null elements.
(probably best explaned by a another code segment)
C#:
void SetupButtons(string[] CAPTIONS,(void(Object,EventArgs))[] CLICKEVENTS)
{
for(int i=0;i<=CAPTIONS.GetUpperBound(0);i++)
{
cmdBUTTON[i].text = CAPTIONS[i];
cmdBUTTON[i].Click += new EventHandler(CLICKEVENTS[i]);
}
}
Once again i know there are other ways of avoiding needing this array, but still, can it be done? and what needs to replace (void(Object,EventArgs)) ?
 
I think your message is more confusing than it needs to be, but as for your SetupButtons method signature, I think it needs to look like

Code:
void SetupButtons(string[] CAPTIONS, EventHandler[] CLICKEVENTS)
 
You probably want to take a look at delegates, these are similar in concept to a function pointer but are typesafe.
A delegate can contain a list of functions, effectively acting as an array - when the delegate is invoked each function in the list will be invoked.
 
PlausiblyDamp

Any chance i could get an example of using delegates.
i tried
delegate void PEVENT(Object Sender,EventArgs e);
PEVENT[] FUNCS = {...};
Compiler did not agree that this was a good solution.
 
You would not need to create an array of delegates, you can simple declare a variable of the delegate type and then add in multiple compatible functions
C#:
		delegate void TestDelegate(string s);

		private void Test1(string s)
		{
		//do something
		}

		private void Test2(string s)
		{
			//do something
		}

		void Example()
		{
		TestDelegate d = new TestDelegate(Test1);
		d+= new TestDelegate(Test2);
		}
 
Back
Top