Home > Software engineering >  Does c# behave differently in function parameter Implicit conversions then direct implicit conversio
Does c# behave differently in function parameter Implicit conversions then direct implicit conversio

Time:07-28

when I am writing in c# (on .net 5) the following code

public class Apple
{
    public int weight { get; set; }
    public Apple(int w)
    {
       weight = w;
    }

    public bool Equals(Apple other)
    {
        return ((other != null) &&(weight == other.weight));
    }
}

in the main function, I declare

Apple a1 = new Apple(10);
Object a2 = new Apple(10);

when I run afterwards the following code Console.WriteLine(a1.Equals(a2)); it will compile and run and return "false" (even though they are the same).

but writing this code a1 = a2; will get a compiler error.

Error CS0266 Cannot implicitly convert type 'object' to 'Apple'. An explicit conversion exists (are you missing a cast?)

can anyone explain what is the difference?

CodePudding user response:

Every object already has an bool Equals(object? obj) method, and you're calling that when you pass an object to your Equals. Instead properly override the built-in Equals

public class Apple
{
    public int weight { get; set; }
    public Apple(int w)
    {
        weight = w;
    }

    public override bool Equals(object? obj)
    {
        if (obj is Apple a )
        {
            return this.weight == a.weight;
        }
        return false;
    }
    public override int GetHashCode()
    {
        return HashCode.Combine(weight);
    }

}
  •  Tags:  
  • c#
  • Related