How do I overload the () operator in C#?

In C++ I can overload the () operator of a structure like this:

struct MyStruct
{
      int            SomeId;
      double      SomePrice_1;
      double      SomePrice_2;
      double      TotalPrice;
      public:
            virtual double operator() (double x)
            {
                  return x + 1.0;
            }
};

This allows me to do this:

      MyStruct ms;
      double y = ms(4);

Doing this leads to y = 5.

I have found various examples of overloading operators in C# but have not be successful with overloading the () operator.  I can overload the [ ] as:

    static class NativeMethods
    {
       public struct MyStruct
       {
          public int SomeId;
          public double SomePrice_1;
          public double SomePrice_2;
          public double TotalPrice;
          public int this[int x]
          {
             get
             {
                return x + 1;
             }
             set
             {
             }
          }
       }
}

Then when I do this:
           NativeMethods.MyStruct myStruct;
           myStruct.SomeId       = SomeId       = 23;
           myStruct.SomePrice_1  = SomePrice_1  = 31.4;
           myStruct.SomePrice_2  = SomePrice_2  = 22.3;
           myStruct.TotalPrice   = TotalPrice   =  0.0;
           double y = myStruct[4];

I get y = 5.

When I try to replace
public int this[int x]
with this:
public int this(int x)
I get various errors.

How do I overload the () operator in C#?
e_livesayAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

jkrCommented:
In short: You can't. See http://msdn.microsoft.com/en-us/library/8edha89s.aspx ("Overloadable Operators (C# Programming Guide)"):

=, ., ?:, ??, ->, =>, f(x), as, checked, unchecked, default, delegate, is, new, sizeof, typeof
      
These operators cannot be overloaded.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
käµfm³d 👽Commented:
I agree with jkr that you cannot overload parens in C#. I wouldn't suggest you do so anyway. The parens signify invoking a method. Using them in conjunction with an object (itself, not a particular method) would make your code hard to read. (The bracket example you show above I definitely advise against. Brackets denote data access, not side effects like adding something to a value.)

Structs in C# (and .NET in general) can have methods the same way that classes can. Just create a new method on your struct that carries out the intended operation. Your maintenance folks will thank you for it  ; )
0
e_livesayAuthor Commented:
Hmm - not at all what I was hoping to hear, but I see what you're saying.

So...this leads me to a different question.  Perhaps it belongs in its own thread but since it is at the root of why I am asking this question, I'll start it here.  I have written a C++ DLL which harnesses some existing C++ code which I have very little desire or need to modify, the Numerical Recipes code for solving differential equations (http://www.nr.com/oldverswitcher.html - in particular page 906 of Press et al., Numerical Recipes, 3rd edition (2007)).  Part of this code expects a structure that overloads the () operator.  It wants a structure of this form:

struct rhs_van
{
   void operator() (double x, vector<double> &y, vector<double> &dydx)
   {
      // Differential equation code goes here.  For example:
      // dydx[0] = y[0];
      // dydx[1] = ((1.0 - y[0]*y[0])*y[1]-y[0]);
   }
}

I have been able to create a structure in a C# driver program and pass it to my C++ DLL according to the instructions in here: http://blogs.msdn.com/b/jonathanswift/archive/2006/10/02/780637.aspx  Doing so lets the C++ code set values within the structure and those new values are seen in the C# code following the call to the C++ code.  This illustrated to me that I am successfully passing a structure from C# to C++.  It seemed that I was one step away - all I needed to do now was modify the structure that I was already creating in C# so that the () operator was overloaded.  However, I seem to be at an impasse.  The Numerical Recipes code expects a structure in which () is overloaded but I can't overload () in C#.

Is there some way to mimic overloading ()?  Am I interpreting the above code incorrectly?

Also, the big picture is this - I am trying to separate the definition of the differential equations (i.e., by putting it in the C# code) from the code that solves them (the C++ code).
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

jkrCommented:
To have the struct 'modifyable' ba native or C++ code, have you tried passing it as 'ref' (and adapting the declarations aslo).

Apart from that, using a delegate to 'redirect' a method call is just semantically different of what you seem to want to achieve..
0
e_livesayAuthor Commented:
I defined the structure in both C# and C++ and successfully passed it by 'ref' from C# to C++.  The C++ code changed some values within it and those changes were seen in the C# code.  All is well there.

Writing a delegate in C# and the C++ code could reference when the C++ code overloads the () operator sounds like a good way forward.  If I understand what you mean I would do this:

In C# I would define a routine along these lines (syntax is not correct):
void foo (double x, vector<double> &y, vector<double> &dydx)
{
      // Differential equation code goes here.  For example:
      // dydx[0] = y[0];
      // dydx[1] = ((1.0 - y[0]*y[0])*y[1]-y[0]);
}

And in C++ I would define the structure of the desired form, and the overloaded () operator would call the C# delegate.  Like this:
struct rhs_van
{
   void operator() (double x, vector<double> &y, vector<double> &dydx)
   {
      // Call the C# foo function
   }
}

I don't know how to implement this because the method that I'm using at the moment is based on defining the same structure in C# and C++ and I currently cannot do this because it is not possible to overload () in C#.  However, that aside, is the above what you're saying?
0
sarabandeCommented:
the method that I'm using at the moment is based on defining the same structure in C# and C++
the equivalence of two structures is defined on their data members not on their operators or functions.

so you should be able to cast a pointer to structure such that the required functionality could be called.

Sara
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.