Overload Appropriate Operators

Discussion in 'C#' started by arunlalds, Mar 13, 2010.

  1. arunlalds

    arunlalds Banned

    Joined:
    Mar 12, 2010
    Messages:
    43
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    student
    Location:
    India
    Operator overloading is like sugar: a little is sweet, but a lot will make
    you sick. Ensure that you only use this technique for situations that make sense.
    Implement operator +
    Notice that the method is public static and takes both operators as arguments.
    Code:
    public static Vertex3d operator +(Vertex3d a, Vertex3d b)
    {
    return new Vertex3d(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
    }
    
    The same principal can be applied to the -, *, /, %, &, |, <<, >>, !, ~, ++, and -- operators
    as well.
    Implement operator == and operator !=
    These should always be implemented as a pair. Because we’ve already implemented a
    useful Equals() method, just call that instead.
    Code:
    public static bool operator ==(Vertex3d a, Vertex3d b)
    {
    return a.Equals(b);
    }
    public static bool operator !=(Vertex3d a, Vertex3d b)
    {
    return !(a==b);
    }
    
    What if the type is a reference type? In this case, you have to handle null values for
    both a and b, as in this example:
    Code:
    public static bool operator ==(CatalogItem a, CatalogItem b)
    {
    if ((object)a == null && (object)b == null)
    return true;
    if ((object)a == null || (object)b == null)
    return false;
    return a.Equals(b);
    }
    public static bool operator !=(CatalogItem a, CatalogItem b)
    {
    return !(a == b);
    }
    
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice