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?
EDIT:
I’m trying to give a class a default operator, something along the lines of:
class A {
A(int myvalue) {/*save value*/}
public static int operator() (A a) {return a.val;}
....
}
...
A a = new A(5);
Console.Write(A());
EDIT 2:
I’ve read the spec and I understand there’s no straight forward way to do this. I was hoping there’s a workaround.
EDIT 3:
The motivation is to make a class, or an instance behave like a function, to make a convenient logging interface. By the way, this is doable and reasonable in C++.
No,(This is incorrect, please see Eric Lippert’s comment below) The parentheses are part of C#’s syntax that are used to express a set of arguments that are passed to a method.()isn’t an operator so it cannot be overloaded.()simply indicates that the method in question specified no formal parameters and therefore requires no arguments.What are you trying to do? Perhaps if you gave a small example of the problem we would be able to help with a solution.
Edit: Okay I see what you are getting at now. You could always create a delegate that maps to the method on the instance like this (given that
class Adefines a method like this:public void Foo() { }):Then you could invoke the delegate with a simple syntax like this:
Unfortunately (or not, depending on your preference) this is pretty much as close as C# will let you get to this kind of syntax.