<?xml version="1.0" encoding="UTF-8"?><item><title>Strings and Nulls in C#</title><description>&lt;DIV&gt;A very common thing in coding is to want to see if you've been given a string or not.&lt;/DIV&gt;&#13;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;&#13;
&lt;DIV&gt;In C#, a string is a reference to an object, and this reference can be null, or it can be a reference to a string, which can contain 0 or more characters.&lt;/DIV&gt;&#13;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;&#13;
&lt;DIV&gt;When you want to see if you have a string or not, you need to first check to see if it's a null reference, and if it's not, then see if the string&amp;nbsp;contains any characters.&amp;nbsp; This ends up looking something like:&lt;/DIV&gt;&#13;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;&#13;
&lt;DIV&gt;&amp;nbsp; if (firstName != null &amp;amp;&amp;amp; firstName.Length &amp;gt; 0)&lt;/DIV&gt;&#13;
&lt;DIV&gt;&amp;nbsp; {&lt;/DIV&gt;&#13;
&lt;DIV&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // do something with firstName&amp;nbsp;&lt;/DIV&gt;&#13;
&lt;DIV&gt;&amp;nbsp; }&lt;/DIV&gt;&#13;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;&#13;
&lt;DIV&gt;If I'm calling a function that doesn't require a first name, I can pass in a null.&amp;nbsp; The disconnect is that if I'm, say, reading data from a text file and the file has a place where the name is going to be, the empty case for the string is simply going to be a string with no characters.&lt;/DIV&gt;&#13;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;&#13;
&lt;DIV&gt;So someone has to say 'this string with no characters is really a null', or everywhere you access the string, you need to see if it's null.&lt;/DIV&gt;&#13;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;&#13;
&lt;DIV&gt;I don't have any great insight to offer here; I just find it less than elegant.&amp;nbsp; I'd like a way to test to see if a string is both non-null and non-empty without having to do the two separate comparisons.&lt;/DIV&gt;&#13;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;</description><pubDate>Thu, 01 Sep 2005 19:17:07 GMT</pubDate></item>