Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Operator = 1

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
0
0
Why it is inpossible to override operator = in C# like C++ ?
Code:
public static void operator = ( MyType mtRight )
{
   ...
}

Thanks
 
Is overriding .Equals() will be call ?
If I'm doing :

Code:
MyType mt = new MyType;
if (mt == mt)
{
 ...
}
Thanks
 
---> Forgot my last message <---
We cannot edit our message in this forum ?


Overriding .Equals() will not be call if I'm doing :

Code:
// Assign another MyType value
MyType mt1 = new MyType();
MyType mt2 = mt1;

// Assign an INT value
int p = 0;
MyType mt3 = p;
But I want to override the operator "=" assignation.
Thanks
 
Operators Overloadability

+, -, *, /, %, &, |, <<, >> All C# binary operators can be overloaded.

+, -, !, ~, ++, --, true, false All C# unary operators can be overloaded.

==, !=, <, >, <= , >= All relational operators can be overloaded,
but only as pairs.

&&, || They can't be overloaded

() (Conversion operator) They can't be overloaded

+=, -=, *=, /=, %= These compound assignment operators can be
overloaded. But in C#, these operators are
automatically overloaded when the respective
binary operator is overloaded.

=, . , ?:, ->, new, is, as, sizeof These operators can't be overloaded

- Neil
 
Some examples
Code:
public static bool operator ==(ThreeDPoint a, ThreeDPoint b)
{
    // If both are null, or both are same instance, return true.
    if (System.Object.ReferenceEquals(a, b))
    {
        return true;
    }

    // If one is null, but not both, return false.
    if (((object)a == null) || ((object)b == null))
    {
        return false;
    }

    // Return true if the fields match:
    return a.x == b.x && a.y == b.y && a.z == b.z;
}

Code:
public static bool operator !=(ThreeDPoint a, ThreeDPoint b)
{
    return !(a == b);
}

I don't believe that you can do equals as = you have to do it as below.
Code:
public override bool Equals(System.Object obj)
    {
        // If parameter cannot be cast to ThreeDPoint return false:
        ThreeDPoint p = obj as ThreeDPoint;
        if ((object)p == null)
        {
            return false;
        }

        // Return true if the fields match:
        return base.Equals(obj) && z == p.z;
    }

    public bool Equals(ThreeDPoint p)
    {
        // Return true if the fields match:
        return base.Equals((TwoDPoint)p) && z == p.z;
    }

----------------------------------------

TWljcm8kb2Z0J3MgIzEgRmFuIQ==
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top