Evorlor
Evorlor

Reputation: 7561

Unity3D, how can I write an extension method for operators?

I am trying to extend Vector3 which is a Unity3D feature. It does not have a less than operator, so I am trying to create one. However, When I write the extension method for it, my IDE tells me "Identifier expected, 'this' is a keyword".

How can I write an extension method using operators? This is my attempt, which unexpectedly did not work:

using UnityEngine;
using System.Collections;

public static class Vector3Extensions
{
    public static bool operator <(this Vector3 vector3, Vector3 other)
    {
        if (vector3.x < other.x)
        {
            return true;
        }
        else if (vector3.x > other.x)
        {
            return false;
        }
        else if (vector3.y < other.y)
        {
            return true;
        }
        else if (vector3.y > other.y)
        {
            return false;
        }
        else if (vector3.z < other.z)
        {
            return true;
        }
        return false;
    }
}

Upvotes: 1

Views: 1027

Answers (2)

Brian Mains
Brian Mains

Reputation: 50728

It's not extension methods but operator overloads. See this MSDN documentation that states:

==, !=, <, >, <=, >= The comparison operators can be overloaded (but see note below). Note The comparison operators, if overloaded, must be overloaded in pairs; that is, if == is overloaded, != must also be overloaded. The reverse is also true, and similar for < and >, and for <= and >=.

Complete documentation here.

Upvotes: -2

Daniel A. White
Daniel A. White

Reputation: 190943

You can not use extension method to overload on operator. Perhaps you can add .LessThan.

Upvotes: 5

Related Questions