Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

C# 

Convert C++ operator methods to C# methods

Im bit confused writing title. If Im wrong then please correct me.

What I want to do is to convert this peace of code to C#

Code
vector2d vector2d::operator*( double num )
{
    vector2d v;
    v.x = num  * x;
    v.y = num  * y;
    return v;
}

double vector2d::operator*( vector2d vec )
{
    return vec .x*x+vec.y*y;
}

vector2d vector2d::operator+(vector2d vec )
{
    vector2d ans;
    ans.x = x + vec.x;
    ans.y = y + vec.y;
    return ans;
}

vector2d vector2d::operator-(vector2d vec )
{
    vector2d ans;
    ans.x = x - vec.x;
    ans.y = y - vec.y;
    return ans;
}

vector2d vector2d::operator-(double num)
{
    vector2d ans;
    ans.x = x - num;
    ans.y = y - num;
    return ans;
}

Its from simple vector2d class. Im making same Vector2D class in C# so I want these functions/methods and I want it to work the same way as it worked in C++.

Seems that I can do - and + operators

Something like this:
Code
Vector2D operator -(Vector2D vec)
{
    Vector2D ans = null ;
    ans.x = x - vec.x;
    ans.y = y - vec.y;
    return ans;
}

But I cant do * operator. It says "Overloadable unary operator expected".
I get this error here:
Code
public double operator *( Vector2D w )
{
    return w.x*x+w.y*y;
}



I have simple multiply methods but it makes my code unreadable so Im trying to convert and use these methods from c++.
You could easily find this with a simple Google query.
Something like:

Code
public static Vector operator *(Vector v1, double num) =>
    new Vector(v1.X * num, v1.Y * num);

Assuming your constructor works like this. If not, just declare a new type and set the properties and return like you do above.
You are lucky that people are willing to spoon feed you.
(Feb 12, 2016 03:11 PM)Forecraft Wrote:  You are lucky that people are willing to spoon feed you.

OP was on the right track and explained his needs well. My code's syntax sugar aside, there isn't much difference between them. Only the corrected version.
(Feb 12, 2016 03:08 PM)Odus Wrote:  Something like:

Code
public static Vector operator *(Vector v1, double num) =>
    new Vector(v1.X * num, v1.Y * num);

Assuming your constructor works like this. If not, just declare a new type and set the properties and return like you do above.

Oh, now I understand. Thanks!


Possibly Related Threads...
Thread / Author Replies Views Last Post
[C] by lockheadApr 22, 2021 07:10 AM 0 147 Apr 22, 2021 07:10 AM
Last Post: lockhead
[C] by pmsSep 29, 2019 05:30 AM 1 251 Sep 29, 2019 05:30 AM
Last Post: YouthInAsia
[C] by F.A.S.TMar 8, 2019 12:38 PM 9 489 Mar 8, 2019 12:38 PM
Last Post: F.A.S.T