Jump to content
  • Advertisement
Sign in to follow this  
BrickInTheWall

C# function pointer problem

This topic is 3195 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi guys, I have a huge amount of code that I want to simplify using delegates. I have an operator token class for operators such as +,-,unary + /- etc. and also functions like sin, cos etc. I would like to store a pointer to the corresponding mathematical function in each instance of the class, but some of these have different signatures. For example the add function would take two double whereas the sin function would only take one. Can anyone give me some advice on how I best solve this? Cheers, Chris

Share this post


Link to post
Share on other sites
Advertisement
In C# 3.0 you can make anonymous functions (aka lambdas):
double Add(double x, double y) { ... }
double Sin(x) { ... }

...

delegate double MyD(double x);

MyD dSin = new MyD(Sin);
y = dSin(6); // call Sin(6) through delegate

MyD dAdd = new MyD(x => Add(x, 5));
y = dAdd(6); // call Add(6, 5) through delegate

Share this post


Link to post
Share on other sites
In general, you don't. Delegates are statically typed, and thus will have a fixed signature. Wanting to store two different signatures in the same variable is a bit of a code smell. You probably want to design slightly differently (because say, you don't want the operation itself, you want a representation of it).

That said, if you're using .NET 4, then you can store the delegates in a dynamic type and then as long as you call them correctly, you're good. Just note that only delegates can be stored, so you explicitly need to go

dynamic op = new BinaryDelegateType(Add);


Just assigning the method, anonymous methods and lambda expressions don't work (yet?).

Share this post


Link to post
Share on other sites
Those are all syntactically valid snippets of C#. I wouldn't say it's the sort of code you'd usually see (idiomatic C# tends to be more verbose).

And no, it doesn't look like VB. It (usually) looks most like Java.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!