C# function pointer problem

Started by
3 comments, last by Telastyn 14 years, 4 months ago
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
Fate fell short this time your smile fades in the summer.
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 delegateMyD dAdd = new MyD(x => Add(x, 5));y = dAdd(6); // call Add(6, 5) through delegate
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?).
Quote:Original post by bubu LV
In C# 3.0 you can make anonymous functions (aka lambdas):
*** Source Snippet Removed ***


This is c#?


I thought c# looked more like VB.
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.

This topic is closed to new replies.

Advertisement