Hack Forums
[C#] Convert C++ operator methods to C# methods - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [C#] Convert C++ operator methods to C# methods (/showthread.php?tid=5168011)



Convert C++ operator methods to C# methods - z1995z - Feb 12, 2016

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++.


* - Forecraft - Feb 12, 2016

You could easily find this with a simple Google query.


* - Odus - Feb 12, 2016

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.


* - Forecraft - Feb 12, 2016

You are lucky that people are willing to spoon feed you.


* - Odus - Feb 12, 2016

(Feb 12, 2016 03:11 PM)Nacorpio 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.


* - z1995z - Feb 12, 2016

(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!