Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does c# behave differently in function parameter Implicit conversions then direct implicit conversion

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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);
    }

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading