Solved

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

Posted on 2014-10-30
6
248 Views
Last Modified: 2014-11-02
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#?
0
Comment
Question by:e_livesay
6 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 500 total points
ID: 40414691
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
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40414802
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
 

Author Comment

by:e_livesay
ID: 40414981
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
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 
LVL 86

Expert Comment

by:jkr
ID: 40414991
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
 

Author Comment

by:e_livesay
ID: 40415002
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
 
LVL 33

Expert Comment

by:sarabande
ID: 40415184
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

Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

785 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question