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.
Related
My C# code-behind looks like this:
if ((DT["BENEFIT_TYPE1"].Equals(0)))
{ DropDownList_Tracking_BenefitType1.SelectedValue = null; }
else if ((DT["BENEFIT_TYPE1"].ToString() = "" ))
{ DropDownList_Tracking_BenefitType1.SelectedValue = null; }
else
{DropDownList_Tracking_BenefitType1.SelectedValue = (DT["BENEFIT_TYPE1"].ToString());}
The code doesn't like the "else if" line; everything inside the parens is underlined in red. When I hover my mouse over it, the popup message is:
The left-hand side of an assignment must be a variable, property or
indexer
Can someone tell me how to fix this? I'm trying to account for NULL values in my dataset.
As Juan pointed out, you need ==, however note that NULL and "" are different things.
You can check for null or empty with:
else if (string.IsNullOrEmpty(DT["BENEFIT_TYPE1"].ToString()))
You are missing a '=' character. In C# comparisions are done with double equal sign '=='. A single one means assignment, hence your error as you cannot assign in a if statement.
Try:
(DT["BENEFIT_TYPE1"].ToString() == "" ))
As other have suggested there are other things to take into account here.
For checking strings to be null or empty you can use the following:
string.IsNullOrEmpty(yourString)
Or if you treat empty space string as empty
string.IsNullOrWhitespace(yourString)
If DT is a datatable that you are sourcing from Database the nulls in database are not null or empty string but DbNull, so you should compare this way:
DT["field"] == DbNull.Value
Or
DT.IsNull("field")
I have just come across this line of C# code and I am not sure what it means:
string sLine = "";
while ((sLine = oStreamReader.ReadLine()) != null)
I assume oStreamReader.ReadLine() is a string too.
My guess is that it is saying whilst neither of the variables are null?
I have searched around but have not been able to find any reference to this kind of notation
My guess is that it is saying whilst neither of the variables are
null?
No it is not comparing both. Instead this line
while ((sLine = oStreamReader.ReadLine()) != null)
means,
Assign the result of oStreamReader.ReadLine to sLine
Check if the result of assignment expression is not equal to null. (That result will be stored in sLine)
It reads all the lines in the stream reader.
Parsing the expression, this is what happens:
oStreamReader.ReadLine() is executed
It's return value is assigned to sLine
The return value of the assignment is compared to null
It's not comparing sLine to null, and it's not comparing oStreamReader.ReadLine() to null either. If sLine was a property that only had a setter, it would still work fine.
The idea is that the assignment operator itself actually has a return value - and that's what's being compared to null.
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
Can you tell me if TrimNull() is redundant and if I should be using an alternative?
For example:
string username = UsernameTextBox.Text.TrimNull();
I am told there is no definition or extension method. Perhaps there is a reference I am missing?
UPDATE:
What is the most readable way to return empty string if the value is NULL?
There's no such function as TrimNull(String) - it wouldn't do anything. A string is either a null or not null, it can't contain a mixture of both. If the string were null, a static function TrimNull(myString) would not be able to 'remove' anything from the string. If it weren't null, there would be no NULL to remove. Even worse, if TrimNull were an instance method myString.TrimNull() would simply cause an exception if myString were NULL - because you cannot invoke any method on a null reference.
If your goal is to trim whitespace characters surrounding the string, just use myString.Trim().
If your goal is to detect whether the string is null, use myString == NULL
If your goal is to detect whether the string is empty or null use String.IsNullOrEmpty(myString)
If your goal is to trim trailing null characters (\0) from data stream, try the following:
myString.TrimEnd(new char[] { '\0' } )
But as Frédéric Hamidi said, if you're referring to the latter, the user will have a hard time getting null characters into a TextBox, so you shouldn't worry about that scenario in your processing of their input.
I usually use String.IsNullOrWhiteSpace(), like this:
string username = (String.IsNullOrWhiteSpace(UsernameTextBox.Text) ?
null : UsernameTextBox.Text.Trim());
That way, if the .Text property is null, it doesn't cause an exception.
You could create your own extension-method for that, if you like:
public static class StringExtensions
{
public static string TrimNull(this string value)
{
return string.IsNullOrWhiteSpace(value) ? value : value.Trim();
}
}
Add this to your project and your code will work.
This is just an alternative.
Use null-coalescing operator as mentioned in #sixlettervariables answer in Negate the null-coalescing operator
string username = (UsernameTextBox.Text ?? String.Empty).Trim();
A string being NULL is not its value. its a state. It means it has not been assigned a memory (coz its a reference type). Had it been a value type datatype it woudld be assigned a default value automatically like for int its 0 and so on
u should use
if(!String.IsNullOrEmpty(UsernameTextBox.Text))
string username = UsernameTextBox.Text.Trim();
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.