In C#: what is the difference between `==` and `Equals()` when comparing objects?
Hello colleagues! I'm a beginner C# developer and I'm facing some confusion. I have a simple Person class with two properties: Name and Age. I created two instances of this class with the same field values. When I compare them using `==`, the result is `false`. But if I use the `Equals()` method, it's also `false`. I expected them to be equal since the data matches. Here's the code:
```csharp
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
Person p1 = new Person { Name = "Alice", Age = 30 };
Person p2 = new Person { Name = "Alice", Age = 30 };
Console.WriteLine(p1 == p2); // false
Console.WriteLine(p1.Equals(p2)); // false
}
}
```
No answers yet.
Log in to leave an answer
Blogs