Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C# support a __call__ method?

Tags:

c#

Python has this magic __call__ method that gets called when the object is called like a function. Does C# support something similar?


Specifically, I was hoping for a way to use delegates and objects interchangeably. Trying to design an API where a user can pass in a list of functions, but sometimes those functions need some initial params, in which case they'd use one of those callable objects instead.

like image 497
mpen Avatar asked Feb 01 '11 03:02

mpen


1 Answers

Sure, if you inherit from DynamicObject. I think you're after TryInvoke which executes on obj(...), but there are several other method you can override to handle casting, index access (obj[idx]), method invocations, property invocations, etc.

using System;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Text;

namespace ConsoleApplication {
    public static class ConsoleApp {
        public static void Main() {
            dynamic x = new MyDynamicObject();
            var result = x("awe", "some");

            Debug.Assert(result == "awesome");
        }
    }

    public class MyDynamicObject : DynamicObject {
        public override Boolean TryInvoke(InvokeBinder binder, Object[] args, out Object result) {
            result = args.Aggregate(new StringBuilder(), (builder, item) => builder.Append(item), builder => builder.ToString());
            return true;
        }
    }
}
like image 157
sisve Avatar answered Oct 20 '22 18:10

sisve