Sign in to follow this  
Telastyn

[C#] Delegate adaptors and/or parameter binding

Recommended Posts

Telastyn    3777
I recently picked up a book on C#, after being capable with C-style languages [C,C++], scripting languages [perl, unix shell], but not functional or Java style languages. One of the neat things with the language is the first rate citizenship of delegates and events. One thing I noticed though that was missing was adapters for them. Coming from C++, I am used to boost::function/bind to be able to adapt functions into certain signatures in a nice generic fashion. In C#, I haven't yet found a nice simple way to do something like this:
class foo{
    public delegate void  foo_d();
    public event    foo_d bar;
    public void     trigger(){bar();}
}

class echo_str{
    public static void     echo(string str){
         Console.WriteLine("{0}",str);
    }
}

class Program{
    static void Main(string[] args){
        foo    eventfoo=new foo();
       
        // Adapt the void(string) to fit into a void()
        eventfoo.bar+=bind(echo_str.echo,"moo.");
        eventfoo.trigger();
    }
}

So, am I just not searching well? Did I miss something that makes this easy? [CreateDelegate doesn't do more than instance binding. Some of the reflection stuff sort of works, but someone already tried that, slowly] Do I just need to wait for someone to do it? Am I missing a good reason I should never have to do this? The lack of operator() overloading, template black magic, and typed templates [template <int> class...] makes the usual methods... difficult.

Share this post


Link to post
Share on other sites
Arild Fines    968
I'd use an anonymous delegate (2.0 only):


class foo{
public delegate void foo_d();
public event foo_d bar;
public void trigger(){bar();}
}

class echo_str{
public static void echo(string str){
Console.WriteLine("{0}",str);
}
}

class Program{
static void Main(string[] args){
foo eventfoo=new foo();

// anonymous delegate here:
eventfoo.bar+= delegate{ echo_str.echo("moo."); };
eventfoo.trigger();
}
}

Share this post


Link to post
Share on other sites
Telastyn    3777
hrm. Yes, that does seem to be the little tidbit that would allow that use. If I used lamdbas more [or if this book spent more than a page on them] that would've been more evident.

Thanks a ton!

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