There are many times in which I have an input text, and, if it's empty (if the user didn't type any text, for example), I want to send a null value to the DB query.
I do not want to send String.Empty. (or "").
Thus I find myself doing this a lot:
var mySqlValue = string.IsNullOrEmpty( tbCustomerId.Text)?null:tbCustomerId.Text;
This seems ugly to me. .NET gives a lot of other solutions for the opposite scenarios:
string.IsNullOrEmpty
string.IsNullOrWhiteSpace
myProblemVal ?? myDefultVal
Is there anything built-in to C# that lets me do this a shorter way, like the opposite direction?
I know this can be solved by writing my own extension methods and I know how to do that; that's not a solution I'm interested in.
I'm looking for some code like "if empty -> null".
.Textis a property (i.e. a call to agetaccessor), the first time the getter is called, it may return a long string, say"John Doe". The we get to evaluate the last "component" of the ternary?:conditional operator. But this calls theTextgetter again, and this time it may return"". So in priciple you have to take a local variable copy ofText. This is not necessary, of course, if you use an extension method.Trim()the string first before checking, which is hard to do in the single expression.