The Time Contains() in C# Broke My Code — A Small Mistake With a Big Impact
Home Sankar Reddy V
June 5, 2025
A Real Bug I Faced
Recently, I ran into a strange bug in my project. I was checking if a certain word existed in a string using the Contains method in C#. Seemed simple enough.
But something wasn’t right. The logic started failing in unexpected ways.
What I didn’t realize was that Contains("admin") also returns true for words like "administrator" or "superadmin". That one small assumption caused a much bigger issue in production.
How Contains Really Works
In C#, string.Contains() checks if a substring is present in the string. It doesn’t care if it’s a full word or part of another word.
It simply looks for "admin" anywhere inside the string. That’s it.
What About List.Contains?
If you’re using Contains on a list (like List<string>), it behaves differently. It checks for exact matches, not substrings.
This is much safer when you’re checking for specific values.
What’s Inside LINQ’s Contains()?
Here’s what Enumerable.Contains() looks like under the hood:
So:
If it’s a collection like a
List, it uses the collection’s ownContains().Otherwise, it loops over each item and uses equality comparison.
It doesn’t check substrings — it checks full object equality.
Safer Alternatives I Now Use
Use
==for Exact Matches
This avoids substring confusion completely.
For case-insensitive comparison:
2. Use Regex for Word Matches
This makes sure "admin" is a standalone word, not part of something else.
3. Split and Search
If you expect words separated by spaces:
What I Learned
We all make silly mistakes like this. I made one — and it had a big impact.
That one line with Contains("admin") gave access to things it shouldn’t have. It reminded me that small details matter in code, especially when it comes to logic and security.
We make simple mistakes which cost a lot of bugs — and those bugs cost time, energy, and sometimes even trust in the system. Always double-check what your code is actually doing, not just what you think it’s doing.
Final Thought
Next time you use Contains, ask yourself:
Am I checking for a part of a word or a full word?
Is
==a better choice?Do I need case sensitivity?
Is the input a string or a collection?
It’s easy to overlook — but this kind of mistake can lead to confusing bugs or worse.
Write your code to be clear, intentional, and unambiguous. You’ll thank yourself later.
