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.
Related
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.
I've got the following code:
// Here is where we will read in all our values and populate the form with them
lblBenCatX.Text = Convert.ToString(reader["Category"]);
lblBenProvX.Text = Convert.ToString(reader["Provision"]);
txtCommentBox.Text = Convert.ToString(reader["Feedback"]);
ddlDefect1.SelectedValue = Convert.ToString(reader["Network"]);
ddlIssue1.SelectedValue = Convert.ToString(reader["Issue_ID"]);
ddlResolution1.SelectedValue = Convert.ToString(reader["Resolution_ID"]);
ddlDefect2.SelectedValue = Convert.ToString(reader["Network2"]);
ddlIssue2.SelectedValue = Convert.ToString(reader["Issue_ID2"]);
ddlResolution2.SelectedValue = Convert.ToString(reader["Resolution_ID2"]);
The first 3 rows of code; no problem. However, if I have a record with a NULL value, the dropdowns break the code. So, I'm thinking I need to check the field first to make sure it's not NULL. Something like:
if (!Convert.ToString(reader["Network"]) = NULL)
{
ddlDefect1.SelectedValue = Convert.ToString(reader["Network"]);
}
However, that's giving me an error:
The left-hand side of an assignment must be a variable, property or
indexer
Any ideas? This is C# in VS2015 with an Oracle back end, if any of that matters.
In C#, you need to use two equal signs in a row == for equality comparison, not one. One equal sign = is an assignment operator.
if (first == second) { ... }
In your case, though, you would want to use the "not equals" != operator:
if (Convert.ToString(reader["Network"]) != null)
Which is cleaner and slightly more-efficent than this:
if (!(Convert.ToString(reader["Network"]) == null))
Note that I've wrapped the whole inner comparison in parens so the whole statement is being negated; otherwise, it will think you're trying to say !Convert.ToString(reader["Network"]), and, as you pointed out in the comments here, you can't use ! with a string.
That being said, if you're converting to string, then it's better to use string.IsNullOrEmpty() for checking:
if (!string.IsNullOrEmpty(reader["Network"].ToString())))
But the best is probably to just check if the column value is null, rather than converting it to string:
if (!reader.IsDBNull(["Network"]))
= is an assignment operator, used when setting values.
== is an equality operator, which determines whether something is equal to something else.
!= is also an equality operator, opposite to the one above. So, when something is not equal to something else.
So actually, you should be using != in this scenario:
if (Convert.ToString(reader["Network"]) != null)
{
ddlDefect1.SelectedValue = Convert.ToString(reader["Network"]);
}
You have a couple of choices. The first is to check if the value is DBNull which is different than an empty string/null value.
if (!reader.IsDBNull([ordinalPositionOfNetworkInSelectStatement]))
ddlDefect1.SelectedValue = Convert.ToString(reader["Network"]);
See IDataReader.IsDBNull. The only thing is that you need to know the ordinal position of the column you are checking.
The alternative is to check for dbnull in your sql select statement and use a function to return an empty string if it is. The positive side of this approach is you do not have to worry about checking for null in your c# code but I am not sure if it has any negative consequences in your oracle query or view. You can do this with COALESCE.
SELECT Category, Provision, Feedback, COALESCE(Network, '') AS Network /*other columns*/
FROM ... -- rest of the query
disclaimer - my oracle syntax is lacking but COALESCE does exist as a function
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 am assigning a value to var in c#
string fileName = properties.AfterProperties["Name"] != null ? properties.AfterProperties["Name"].toString(): "";
Now the problem i face is fileName is null irrespective of the value of properties.AfterProperties["Name"]
I checked value of properties.AfterProperties["Name"] which had fileName and i also checked the entire assignment statement in the immediate window and it assigning the value of properties.AfterProperties["Name"] to the fileName
But when i press f11 after that assignment line, the value of fileName is null!!
You may try this as well
string fileName = properties.AfterProperties["Name"] != null && !String.IsNullOrEmpty(properties.AfterProperties["Name"].toString()) ? properties.AfterProperties["Name"].toString(): "";
By the way small hint:
properties.AfterProperties["Name"] != null // This check avoids object reference errors.
!String.IsNullOrEmpty(properties.AfterProperties["Name"].toString()) // This check will avoid your problem - returning empty instead of null.
Hope this helps.
It depends on the type of AfterProperties.
In the first condition you used properties.AfterProperties["Name"], but in the assignment you used properties.AfterProperties["Name"].ToString()
Maybe properties.AfterProperties["Name"] is not null but properties.AfterProperties["Name"].ToString() returns null.
May be trying like this:
string fileName = !properties.AfterProperties["Name"].Equals(null) ? properties.AfterProperties["Name"].toString(): "";
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.