Conditional operator not working as expected - c#

I have the following code where I am using a Conditional Operator to look for null values and assign another value if a null is found. My problem is that it isn't detecting the null value correctly for some reason.
sliderQuestion11.Value = Convert.ToDouble(cs.q11 != null ? cs.q11 : "10");
cs is a class populated by a SQLite query and q11 is a string.
I get a "Value cannot be null" error. Thanks.
EDIT
Thanks for the help everyone. All those answers should have worked but what I had to do is instead of just returning
query.FirstOrDefault()
I had to do the following
CustomerSurvey cs = new CustomerSurvey();
cs.q1 = query.FirstOrDefault().q1 ?? "-10";
cs.q2 = query.FirstOrDefault().q2 ?? "-10";
cs.q3 = query.FirstOrDefault().q3 ?? "-10";
cs.srID = query.FirstOrDefault().srID;
Now this works
sliderQuestion11.Value = Convert.ToDouble(cs.q11 != "-10" ? cs.q11 : "10");
(I know you are going to say why not just set it to 10 but I need to detect a null value elsewhere in the code. That is why I'm using -10)

Maybe you need:
!string.IsNullOrEmpty(cs.q11) ? cs.qll : "10";
The reason for using string.IsNullOrEmpty is because the string may just be empty rather than null.
Full snippet:
sliderQuestion11.Value = Convert.ToDouble(!string.IsNullOrEmpty(cs.q11) ? cs.qll : "10");

You could also try this code:
sliderQuestion11.Value = Convert.ToDouble(cs.q11 ?? "10");

Perhaps it should be
sliderQuestion11.Value = (cs != null && (!string.IsNullOrWhitespace(cs.q11)) ? Convert.ToDouble(cs.q11) : 10);

sliderQuestion11.Value = Convert.ToDouble(!string.IsNullOrWhiteSpace(cs.q11) ? cs.q11 : "10");
This would also check that the string does not contain just 1 or more whitespaces, in addition to the null and empty checks.

Yet another answer: :)
sliderQuestion11.Value = string.IsNullOrWhitespace(cs.q11) ? 10.0 : Convert.ToDouble(cs.q11);

Related

Check if a BsonValue is not null

Take for example the following extract from a mongo collection :
{"IsBasedOnProduct" : {
"CodeUV" : "09184",
"Name" : null,
"pricingVersion" : "B"
}
}
I would like to extract the Name field from this collection and put it in a C# object. But i do not know how to manage the null value.
This is what I am doing in my C# application :
if (foo.Contains("IsBasedOnProduct"))
{
fooToExcel.Name = foo["IsBasedOnProduct"].AsBsonDocument.Contains("Name") ? foo["IsBasedOnProduct"]["Name"].AsString : string.Empty;
}
Of course when the Name is null, i throw an System.ArgumentNullException
How can I fix it in order to put string.Empty when the value is null ?
Fix it using the following snapshot of code :
if (foo.Contains("IsBasedOnProduct") && foo["IsBasedOnProduct"].BsonType != BsonType.Null)
{
fooToExcel.Name = foo["IsBasedOnProduct"].AsBsonDocument.Contains("Name")&& foo["IsBasedOnProduct"]["Name"].BsonType != BsonType.Null ?
foo["IsBasedOnProduct"]["Name"].AsString : string.Empty;
}
Before that you have to Convert BJson to JSON, check after the conditions.
#Xavier W answer correct Also there another solution to check was BsonValue is NULL using IsBsonNull property [since MongoDB.Bson version 2.3.0]
Here solution:
if (foo.Contains("IsBasedOnProduct") && !foo["IsBasedOnProduct"].IsBsonNull)
{
fooToExcel.Name = (foo["IsBasedOnProduct"].AsBsonDocument.Contains("Name") && !foo["IsBasedOnProduct"]["Name"].IsBsonNull) ?
foo["IsBasedOnProduct"]["Name"].AsString : string.Empty;
}
Documention for IsBsonNull Property -> https://mongodb.github.io/mongo-csharp-driver/2.3/apidocs/html/P_MongoDB_Bson_BsonValue_IsBsonNull.htm

What does this code with "?" and "??" mean?

What does this syntax mean? I'm currently coding c# 4.0, when I came by this piece of code.
_data = (SerializationHelper.Deserialize(Request.Form[_dataKey])
? TempData[_dataKey] ?? new ProfileData ()) as ProfileData;
If I were to write it i IF statements how would it be then?
The compiler gives me an error for not writing a : aswell as more things are needed?
?? means if it's null, use the other value. For example
var name = somevalue ?? "Default Name";
If somevalue is null, it will assign the value "Default Name"
Also the single ? is a ternary operator, basically you use it like this:
var example = (conditional statement here) ? value_if_true : value_if_false;
However your code doesn't seem to follow the right syntax for ternary operators when I look at it properly, as Corey says, you may have missed a ? off a ??.
Looks like you missed a ? there. I suspect it was supposed to read:
_data = (SerializationHelper.Deserialize(Request.Form[_dataKey])
?? TempData[_dataKey]
?? new ProfileData()
) as ProfileData;
In C# the operation A ?? B is directly equivalent to (A == null ? B : A), or if (A == null) return B; return A; if you prefer.
So your statement above is equivalent to:
object tmp = SerializationHelper.Deserialize(Request.Form[_dataKey]);
if (tmp == null)
{
tmp = TempData[_dataKey];
if (tmp == null)
_tmp = new ProfileData();
}
_data = tmp as ProfileData;

Problem with operator?

I am writing following code:
_normDoc = value as NormDoc;
if(_normDoc != null)
{
ucRusKazTextBoxesAnnotation.Controls["tbNameRu"].Text = _normDoc.AddInfoRu ?? string.Empty;
}
I think that if _normDoc.AddInfoRu == null then ucRusKazTextBoxesAnnotation.Controls["tbNameRu"].Text will be equal empty string.
But I am got error: NullReferenceException.
Can you explain me why?
PS. ucRusKazTextBoxesAnnotation not equal null;
EDIT: Sorry, I find error, yes, tbNameRu not found, because they are inside Panel control.
Make sure that ucRusKazTextBoxesAnnotation.Controls["tbNameRu"] is not null.
ucRusKazTextBoxesAnnotation.Controls["tbNameRu"] could be null just as well.

using the ?? operator and dealing with a null value

I am returning a scalar value from a SQL Server 2008 database:
string reason = cmd.ExecuteScalar().ToString() ?? : "";
I want to make sure that if null is returned, that reason = "" and not null.
i am getting an error on this line:
Error 3 Invalid expression term ':'
How can this be fixed?
EDIT:
thank you for the changes on the colon, now i am getting this exception on the same line:
string reason = cmd.ExecuteScalar().ToString() ?? "";
System.NullReferenceException occurred
Message="Object reference not set to an instance of an object."
Try this:
string reason = cmd.ExecuteScalar().ToString() ?? "";
BUT: this will still fail, since if .ExecuteScalar() returns a NULL, you're already causing a Null Reference Exception by calling .ToString() on that NULL value......
So I guess the ?? operator really doesn't help you here... do the "usual" dance:
object result = cmd.ExecuteScalar();
if(result != null)
{
reason = result.ToString();
}
else
{
reason = "(NULL value returned)";
}
First, you shouldn't have the : when using the ?? operator.
Second, to do what you are trying to do here without getting an error, you need to do it differently:
object objReason = cmd.ExecuteScalar();
string reason = objReason == null ? "" : objReason.ToString();
This will check whether or not your returned value is null and if it is, the second line will set reason to a blank string, otherwise it will use your returned value.
Since ExecuteScalar() returns object that might be null you should not call .ToString() since that may throw and exception.
string reason = Convert.ToString(cmd.ExecuteScalar());
This works because Convert.ToString() will convert null to string.Empty
or if you must use ?? because you really like it:
(cmd.ExecuteScalar() ?? (object)"").ToString();
Just get rid of the colon.
string reason = cmd.ExecuteScalar().ToString() ?? "";
For reference, check the MSDN page.
When using the null-coalescing operator, you don't need the colon:
string reason = cmd.ExecuteScalar().ToString() ?? "";
As others have pointed out though, ToString() would cause a NullReferenceExcpetion to be thrown anyway...so you don't gain anything here. You'd be much better off splitting this into multiple lines:
var result = cmd.ExecuteScalar();
string reason = result == null ? "" : result.ToString();
You're confusing the ? conditional operator, the syntax for which looks like this:
String x = condition ? valueIfConditionIsTrue : valueIfConditionIsFalse;
with the ?? null-coalesce operator whose syntax is as follows:
String x = possiblyNull ?? valueIfPossiblyNullIsNull;
So, apart from all that... this is the part you really want:
String reason = (cmd.ExecuteScalar() ?? "").ToString();
This takes care of your exception where ToString() was causing a null-reference exception.
Just use
string reason = cmd.ExecuteScalar() ?? "";

Setting a default value when getting XML values via Linq

I’m using Linq to extract values from some XML. Shown below is a simplified example to show the problem I’m having. The following code works fine on the XML shown below. The problem I have is when the groupBy section is missing. Because when it’s missing Data.Element("groupBy").Element("property) fails because Data.Element("groupBy") will be null. Is it possible to modify my Linq statement to allow it to provide a default or should it be approached in a different way?
var e = (from Data in theXML.Descendants("exportFile")
select new Export
{
OutputFileName = Data.Element("outputFileName") != null ? (string)Data.Element("outputFileName") : "",
GroupByProperty = Data.Element("groupBy").Element("property") != null ? (string)Data.Element("groupBy").Element("property") : ""
}).First();
<exportFile>
<outputFileName>output.xml</outputFileName>
<groupBy>
<property>DeviceId</property>
</groupBy>
</exportFile>
You can already make it slightly nicer than it is using the null coalescing operator. However, to cope with the groupby element being missing is harder:
select new Export
{
OutputFileName = (string) Data.Element("outputFileName") ?? "",
GroupByProperty = Data.Element("groupBy") == null ? ""
: (string) Data.Element("groupBy").Element("property") ?? ""
}).First();
The conversion to string just returns null if the element reference is null.
An alternative would be:
GroupByProperty =
(string) Data.Elements("groupBy").Elements("property").FirstOrDefault() ?? ""
That uses the extension method which allows you to call Elements on an IEnumerable<XElement>... so that will (lazily) evaluate a sequence of every property element under a groupBy element under Data, then take the first of them if any exist, then apply the string conversion.
You could simply add an additional check in the statement (and clean things up a bit using the null coalescing operator):
GroupByProperty = Data.Element("groupBy") != null ?
(Data.Element("groupBy").Element("property") ?? "") : "";

Categories