What is the best way of testing that a string is empty? - c#

I usually do this:
void Incoming(String str)
{
if (str == "")
{
}
}
But I've seen others' code do this:
void Incoming(String str)
{
if (str == String.Empty)
{
}
}
In my case I know str shouldn't be null. So would the following be a good idea instead, given it will cause an exception if the string is null rather than hiding the problem:
void Incoming(String str)
{
if (str.Length == 0)
{
}
}
And I've noticed this being used too, but this seems to accept the string might be null, rather than going and fixing the reason it is null. Is it a good idea to silently handle strings being null?
void Incoming(String str)
{
if (String.IsNullOrEmpty(str))
{
}
}

if(String.IsNullOrEmpty(str1))
{
//do stuff
}
Always use this!

What is the best way of testing that a string is empty?
Your last option String.IsNullOrEmpty(str) is best to do so. It checks for both condition
If string is null
If your string is equal to String.Empty i.e. "".

If the string should never be null, do an explicit null check before testing whether it's empty.
if (string == null) throw new Exception(); // ArgumentNullException, for example
if (string == "")
{
...
}

Generally you should not use Exceptions for System flow. So if the String can (but shouldn't) be null, then check for NullOrEmpty and fix it there.
Whats the matter for checking if it is NULL or Empty? Both will cause some fixing Code or you can throw your own "IHateNullStrings"-Exception.
If you want the total safety:
String.IsNullOrWhiteSpace
With this one you check
Null
Empty
Only WhiteSpace characters
Edit: Exception Flow is the path the program passes. Using exception for "Could happen"-things makes f.e. debugging way more complicated.
There is a huge discussion about this, f.e. :Why not use exceptions as regular flow of control?

Although you say str should not be null, you are relying on something external to adhere to that, which is not a good idea. Also, letting an exception be thrown in the if block is not a great idea because:
Exceptions are expense, so should be avoided where possible
The default exception is not going to give the caller much context as to what they have done wrong. So if you really need an exception, throw one yourself with something meaningful (I.E. ArgumentNullException) with a useful message
so with the above said you can either do a seperate null check:
if (str == null) throw new ArgumentNullException("str cannot be null");
or you can treat null and string.Empty as equal and use (which would be my default):
if (string.IsNullOrEmpty(str))
{
//do something
}
or you can even treat blank strings the same as null and empty by using:
if (string.IsNullOrWhiteSpace(str))
{
/do something
}
It largely depends on what your logic is when you get empty strings. However you should always be writing some defensive code to deal with arguments not fulfilling the pre-conditions

Related

How to recognize a null sting

I have a string TempDayValues[j] that holds a null value but the following two examples do not recognize the null
string Temp = TempDayValues[j].Trim();
if (string.IsNullOrEmpty(Temp))
{
Console.WriteLine("Found Null");
TempDayValues[j] = TempDayValues[j - 1];
}
If(Temp == null)
{
//code here
}
Is there any better way to recognize null values?
Comparing with null is the way to check for it. However in your code, if you have not gotten already a NullReferenceException when calling Trim then your string is not null.
Might be that you are looking for IsNullOrWhiteSpace:
if (string.IsNullOrWhiteSpace(TempDayValues[j]))
{
Console.WriteLine("Found Null");
TempDayValues[j] = TempDayValues[j - 1];
}
If you first want to check if it is null and have one behavior and a different if it is empty/white space:
if(TempDayValues[j] == null)
{
// code
}
else if(TempDayValues[j].Trim() == string.Empty)
{
// code
}
Your question, while valid, is missing an explanation of what you're trying to accomplish. Since you've only asked about null checking; my answer only focuses on the null checking that is performed in your code snippet.
There are a few things to remark about your code that I think will help you understand the situation better.
String Temp = TempDayValues[j].Trim();
It's interesting to see that you have already called .Trim() on the string. If TempDayValues[j] was null, this would throw an exception. You can't call methods on null values (you also can't access properties and fields on a null value).
If your application is not throwing an exception; which I assume it is not as you have not mentioned it; then you have implicitly already "proven" that your string is not null. Because you would get an exception otherwise.
Also note that .Trim() will never make something null. Since you are only interested in checking if TempDayValues[j] is null (and potentially overwriting the value, but never using the value); it is functionally irrelevant to use .Trim() for the purpose of null checking.
Let's assume for the rest of the explanation that it is possible for your string to be null; even though .Trim() has made it impossible in your example.
if (string.IsNullOrEmpty(Temp))
{
Console.WriteLine("Found Null");
TempDayValues[j] = TempDayValues[j - 1];
}
Your if block will be executed if your string is null, but also if it is empty. You are, after all, calling the method string.IsNullOrEmpty(). An empty string is a string that is not null, but also does not contain any characters.
So a more correct message would be "found null or empty string".
if(Temp == null)
{
//code here
}
While this is a valid method of checking for null; the if block will not execute if your string is empty. This might be what you are looking for. In most cases, I would expect String.IsNullOrEmpty() to be more suited; but I'm not aware of the specific purpose of your code.
Here, it would be correct to say that you "found null" and NOT an empty string.
That being said; what is the answer to this problem?
This isn't easy to answer; as you've not explained the intention of the code snippet. I am going to offer a code improvement, it's the best I can give you without more info.
string Temp = TempDayValues[j];
if (string.IsNullOrEmpty(Temp)) //use Temp == null here if you don't want it to trigger on empty strings.
{
Console.WriteLine("Found Null or empty string");
TempDayValues[j] = TempDayValues[j - 1];
}
edit If you also need this if block to be executed for cases where your string is not null, not empty, but it only contains whitespaces; then it is relevant to call .Trim(). In that case, change your if block to:
if (string.IsNullOrEmpty(Temp) || string.IsNullOrEmpty(Temp.Trim()))
If Temp is null, only the left operand will be executed (because it makes the evaluation result true regardless of the right operand).
The right operand will be executed only if your string is not already null or empty. In that case, it allows you to check for a string that contains only whitespace characters.

c# multiple if conditions in same lane

I have a slight problem when working with c# and using IF statments with multiple conditions.
This is the most common occurance.
private void SomeFunction(string SomeString)
{
if(SomeString != null && SomeString.Trim() != "")
{
}
}
In some languages like javascript if the first argument fails (SomeString != null) the second check wont be made. C# seems to check both arguments even if the first one fails and then the second one will throw an exception since you cannot use .Trim() on a null value.
Right now I am going over this by nesting my ifs which is messy work. Like this:
private void SomeFunction(string SomeString)
{
if(SomeString != null)
{
if(SomeString.Trim() != "")
{
.....
}
}
}
Does anybody have any suggestions or best practices on a better way to solve this?
C# seems to check both arguments even if the first one fails
That's not true, see && Operator (C# Reference) in MSDN.
Your assumption is totally wrong. When you use the conditional AND if the first condition is FALSE the second condition is never evaluated or executed. In the conditional OR if the first condition is TRUE the second one is never evaluated or executed.
In other words, if the compiler has enough info to determine the result of the expression it stops to consider the second part of the expression.
This is known as short-circuit evaluation.
It is a basic programming principle for C derived languages but also for every other major language.
There is a better way:
private void SomeFunction(string SomeString)
{
if (!string.IsNullOrWhiteSpace(SomeString))
{
// your code
}
}
if (!String.IsNullOrEmpty(SomeString))
{
}
if(!string.IsNullOrEmpty(SomeString))
similar to ProgramFOX prefer this if you insist on doing ".Trim()"

Handling null in extension method

I have a simple extension method for string class which will strip all non numeric characters from a string. So if I have a string like for example a phone number such as "(555) 215-4444" it will convert it to "5552154444". It looks like this:
public static string ToDigitsOnly(this string input)
{
Regex digitsOnly = new Regex(#"[^\d]");
return digitsOnly.Replace(input, String.Empty);
}
I am just wondering what is the most elegant way to handle a null value here? Is there a typical pattern to follow in these cases, such as return back a null value if a null is passed in? It seems since I'm extending the string class here I may want to allow null values and not throw a arguement exception (since I'm not really passing in an arguement when I use this...) ? But some might argue I should throw an exception like a 'normal' method would. What's the best practice you are using here?
Thanks!
You can follow the principle of least surprise: use pattern implemented in LINQ:
public static string ToDigitsOnly(this string input)
{
if(input == null)
throw new ArgumentNullException("input");
Regex digitsOnly = new Regex(#"[^\d]");
return digitsOnly.Replace(input, String.Empty);
}
You can use method, proposed by Jon Skeet. It will reduce your check simply to
input.ThrowIfNull("input");
Also Jon has a good section 10.2.4 Calling a method on a null reference in C# in Depth, quote:
CHECKING FOR NULLITY As a conscientious developer, I’m sure that your
production methods always check their arguments’ validity before
proceeding. One question that naturally arises from this quirky
feature of extension methods is what exception to throw when the first
argument is null (assuming it’s not meant to be). Should it be
ArgumentNullException, as if it were a normal argument, or should it
be NullReferenceException, which is what would’ve happened if the
extension method had been an instance method to start with? I
recommend the former: it’s still an argument, even if the extension
method syntax doesn’t make that obvious.
I see this recommendation as (and from my personal experience): it's always better to check for null, specially for static methods and do not to rely on null values. One exception only if it is the exact purpose of your method, for example ThrowIfNull or IsNullOrEmpty extension methods.
It doesn't really matter as long as you communicate the behavior well (so that the end-user knows what to expect).
Consider using the built-in XML Documentation Comments to communicate expected behavior.
/// <exception cref="ArgumentNullException">argument is null.</exception>
public string Example( string argument )
{
if ( argument == null )
throw new ArgumentNullException();
return argument.ToString();
}
See MSDN documentation for many examples:
DateTime.ParseExact Method (String, String, IFormatProvider)
Uri.FromHex Method
Suppose I have this:
class A
{
public void F()
{
//do stuff
}
}
If I then run the following code, what happens?
A a = null;
a.F();
You get a NullReferenceException. So I would say the proper way to write an equivalent extension method would be as follows.
class A
{
}
static class AExtensions
{
void F(this A a)
{
if (a == null)
{
throw new NullReferenceException();
}
//do stuff
}
}
However, .NET disagrees with me on this. The standard in .NET is to instead throw an ArgumentException - so it's probably best to do that instead.
Simple ; Create another method for String , say IsInValid()
public static bool IsInValid(this string s)
{
return (s == null) || (s.Length == 0);
}
use whereever you wanna check...
Furthermore, you can use this extension anywhere

How to default null session values to blank strings in C#

I'm used to using VB.net for web programming.
Often, I have something like:
Dim s as string = Session("s")
I get a string value for s from the web session. If there is no value in the web session, I get a blank string.
However, AFAIK, in C#, I have to have something like the code below to do the same thing.
string s;
try { s = Session["s"].ToString(); }
catch { s = ""; }
Is there an easier way to do this?
This is a quick way of doing this:
s = (string)Session["s"] ?? "";
This will cast Session["s"] to a string, and if it is not null, return the value. If it is null, it will return an empty string. The "a ?? b" expression is essentially the same as "a != null ? a:b" (?? is compiled more efficiently though)
Something else to keep in mind: you should never use exceptions for normal application logic.
Because string is reference type then is nullable, so you can check for empty or null by means of string.IsNullOrEmpty(s):
string s = string.IsNullOrEmpty((string)strObject) ? string.Empty : strObject.ToString();
Otherwise (as Philippe Leybaert says) you can use ?? operator.
I almost agree to Philippe, but it only works if "s" is present in the session, otherwise there will be a KeyNotFoundException. This code checks it, but does not solve the NULL issue of Philippe.
s= Session.ContainsKey("s")?Session["s"]:"";
So to cover both possibilities, it becomes mre complex:
s = Session.ContainsKey("s")?(Session["s"]??""):"";
It does not really make it easier, but the performance should be better than catching an exception.

Null and blank values

What's the best way of writing robust code so that a variable can be checked for null and blank.
e.g.
string a;
if((a != null) && (a.Length() > 0))
{
//do some thing with a
}
For strings, there is
if (String.IsNullOrEmpty(a))
You can define an extension method to allow you to do this on many things:
static public bool IsNullOrEmpty<T>(this IEnumerable <T>input)
{
return input == null || input.Count() == 0;
}
It already exists as a static method on the System.String class for strings, as has been pointed out.
And if you are using .NET 4.0 you might want to take a look at String.IsNullOrWhiteSpace.
From version 2.0 you can use IsNullOrEmpty.
string a;
...
if (string.IsNullOrEmpty(a)) ...
if(string.IsNullOrEmpty(string name))
{
/// write ur code
}
for strings:
string a;
if(!String.IsNullOrEmpty(a))
{
//do something with a
}
for specific types you could create an extention method
note that i've used HasValue instead of IsNullorEmpty because 99% of the times you will have to use the !-operator if you use IsNullOrEmpty which I find quite unreadable
public static bool HasValue(this MyType value)
{
//do some testing to see if your specific type is considered filled
}
I find Apache Commons.Lang StringUtils (Java)'s naming a lot easier: isEmpty() checks for null or empty string, isBlank() checks for null, empty string, or whitespace-only. isNullOrEmpty might be more descriptive, but empty and null is, in most cases you use it, the same thing.

Categories

Resources