locked
Operator Overloads for Windows.Foundation.Point

    Question

  • In my app, I have a number of scenarios in which I want to add 2 Points to do something like the following:

    New Point(pt1.X + pt2.X, pt1.Y + pt2.Y)
    I would like to be able to do this using the + operator for something like:
    pt1 + pt2
    But the + operator is not defined for the Point Structure, so I would need to do it myself. I have done operator overloading before, but only for my own classes and structures. I could obviously write an extension method or create a shared function, but those seem like more effort than they are worth for something as simple as Point. Is it possible to do operator overloading for an existing Structure, or am I stuck with one of the other techniques? Thanks.

    Nathan Sokalski njsokalski@hotmail.com http://www.nathansokalski.com/

    Tuesday, May 13, 2014 4:09 PM

Answers

All replies

  • Hi, you can try extension method:

    Module PointExt
        <System.Runtime.CompilerServices.Extension> Public Function Add(p1 As Point, p2 As Point) As Point
            Return New Point(p1.X + p2.X, p1.Y + p2.Y)
        End Function
    End Module
    Dim p1 = New Point(1, 2)
    Dim p2 = New Point(3, 4)
    Dim p3 = p1.Add(p2)


    Wednesday, May 14, 2014 6:12 AM
  • Hi Nathan,

    Probably you can't.

    I'm trying to find some documentation that can explain why.

    --James


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.


    Wednesday, May 14, 2014 6:17 AM
    Moderator
  • Like I said in my original post, I feel that in this case an extension method is more effort than it is worth. My reason for wanting an operator is not so much for simplifying the code but to make it easier to read (it is much easier to pick out a + than any function name, even one as simple as Add).

    Nathan Sokalski njsokalski@hotmail.com http://www.nathansokalski.com/

    Wednesday, May 14, 2014 2:59 PM
  • Operator overloads must be defined in the class they operate on. Since you can't modify the Point class you can't add an operator to it.

    See the Data Type Restrictions section at http://msdn.microsoft.com/en-us/library/hddt295a(v=vs.120).aspx

    Thursday, May 15, 2014 12:36 PM
    Owner