List.Find<T>() returning null even though predicate matches

.net, c#

Solution

The problem is that the type of `CommandArgument` is `object`, so it's performing a reference identity check. (I'm surprised this isn't giving you a compile-time warning.)

You could either cast `CommandArgument` to `string`, or use `Equals`:

u => u.Username == (string) args.CommandArgument

or

u => Equals(u.Username, args.CommandArgument)

(Using the static `Equals` method this way means it'll work even for users with a `null` username, unlike `u.Username.Equals(args.CommandArgument)`.)

I wouldn't convert the sequence to a list though - I'd just use LINQ instead:

DomainUser toRemove =
    repo.FirstOrDefault(u => u.Username == (string) args.CommandArgument);

Problem

I'll just attach a picture for reference on this one. I am stumped. In the debugger, the values definitely equal each other, but `Find<T>` is still returning null and `Exists<T>` is still returning false. For reference: `UserRepository` implements `IEnumerable<T>` where `T` is `DomainUser`.

Original source