Is it possible to overload the default function operator (the () operator) in C#? If so - how? If not, is there a workaround to create a similar affect?
Thanks,
Yes, this can be absolutely be done with the dynamic
type (more info found here).
using System.Dynamic.DynamicObject
class A : DynamicObject
{
private int val;
A(int myvalue)
{
this.val = myvalue;
}
public override bool TryInvoke(InvokeBinder binder, object[] args, out object result) {
result = this.val;
return true;
}
}
...
dynamic a = new A(5);
Console.Write(a());
The dynamic
type means that the type is assumed entirely at runtime allowing for a greater flexability to almost every interaction with the object.
I have assumed you meant to use a
rather than A
in the Console.Write
line.