I believe I should be using null-coalescing for this:
fNameSearch.ToUpper() ?? *
Your belief is false. It only makes sense to use ??
when the left hand side can possibly be null. If fNameSearch
is null then the call to ToUpper()
throws; if it is not null then the call to ToUpper()
produces a non-null string. So the ??
operator is not what you want to use.
The operator you're looking for is the lifted nullable member access operator:
fNameSearch.?ToUpper() ?? "test"
This means "if fNameSearch
is null then produce null, give that to the ??
operator and get "test"
; if it is not null then call ToUpper()
, which will produce non-null string.
Unfortunately the .?
operator does not exist in C#. It is a frequently requested feature, so perhaps a future version of the language will have it.
but I want to be able to return everything, not just "test".
Then you don't want either operator.
Take a step back. State what you want the predicate's behaviour to be.
- if
fNameSearch
is null then match everything
- otherwise, match
firstName.ToUpper().Contains(fnameSearch.ToUpper)
OK, that's an easy predicate to write.
s => fNameSearch == null || s.firstname.ToUpper().Contains(fNameSearch.ToUpper())
So is this code correct?
No. ToUpper
is not a good way to canonicalize a name. Remember, names are cultural artifacts and therefore must be searched using the correct rules for the culture associated with the name.
The correct way to do this is to obtain the CultureInfo
object for the culture that the name is written in, and then call
culture.CompareInfo.IndexOf(firstname, fNameSearch, CompareOptions.IgnoreCase)
and see if it comes back with a valid index or not.
Also, you probably should read this article before you write more code that tries to canonicalize names.
http://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/