Any reason to prefer getClass() over instanceof when generating .equals()?

I’m using Eclipse to generate .equals() and .hashCode(), and there is an option labeled “Use ‘instanceof’ to compare types”. The default is for this option to be unchecked and use .getClass() to compare types. Is there any reason I should prefer .getClass() over instanceof? Without using instanceof: if (obj == null) return false; if (getClass() … Read more

What’s the difference between IEquatable and just overriding Object.Equals()?

I want my Food class to be able to test whenever it is equal to another instance of Food. I will later use it against a List, and I want to use its List.Contains() method. Should I implement IEquatable<Food> or just override Object.Equals()? From MSDN: This method determines equality by using the default equality comparer, … Read more

Compare two List objects for equality, ignoring order [duplicate]

This question already has answers here: Comparing two collections for equality irrespective of the order of items in them (20 answers) Closed 4 years ago. Yet another list-comparing question. List<MyType> list1; List<MyType> list2; I need to check that they both have the same elements, regardless of their position within the list. Each MyType object may … Read more

Comparing two strings, ignoring case in C# [duplicate]

This question already has an answer here: What is difference between different string compare methods [duplicate] (1 answer) Closed 2 years ago. Which of the following two is more efficient? (Or maybe is there a third option that’s better still?) string val = “AStringValue”; if (val.Equals(“astringvalue”, StringComparison.InvariantCultureIgnoreCase)) OR if (val.ToLowerCase() == “astringvalue”) ? 8 Answers … Read more