Sign in to follow this  
BrickInTheWall

C# function pointer problem

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this