there are many times in which I have an input text ,
and if its empty ( user didnt type any text ) - i want to send to the DB query "null"
and not String.Empty.
( or "")
so i find my self 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
I know this can be solved by Extension methods - and i know how to do it..
but is there anything better ?
is there any intelligent code for : "if its empty -> null
".
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.
Because a and b and c , so it's name is C. C came out of Ken Thompson's Unix project at AT&T. He originally wrote Unix in assembly language. He wrote a language in assembly called B that ran on Unix, and was a subset of an existing language called BCPL.
You can use an extension method:
public static class Extensions { public static string NullIfWhiteSpace(this string value) { if (String.IsNullOrWhiteSpace(value)) { return null; } return value; } }
Which you could use like that:
var mySqlValue = tbCustomerId.Text.NullIfWhiteSpace();
I don't really know what you imagine by something better than Extension methods. How do you define "better"? Shorter? Using a special keyword? Using rarely used operators to look clever? This is already just a single method call appended to your value, which even works on null values, and the logic you need can't really be expressed in a shorter way than this. Also, I don't know of any special syntax for it.
but is there anything better ?
No, although I'd argue that what you describe in the question (extension methods) is absolutely fine. And as you describe in the question, in the other direction you have null-coalescing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With