How can I used BeEquivalentTo to make null equivalent to empty? - c#

How can I used BeEquivalentTo to compare ActualObject.Flied=null and ExpectedObject.Filed = String.Empty and get they are equivalent? I am looking for something like
ActualObject.Should().BeEquivalentTo(ExpectedObject,????)
Context:
ActualObject.Flied = null
ExpectedObject.Filed = String.Empty
I tried:
ActualObject.Should().BeEquivalentTo(ExpectedObject)
but I get an error:
ActualObject.Name to be <null>, but found ""

Related

Conditional operator not working as expected

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);

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() ?? "";

how can I check whether the session is exist or with empty value or null in .net c#

Does anyone know how can I check whether a session is empty or null in .net c# web-applications?
Example:
I have the following code:
ixCardType.SelectedValue = Session["ixCardType"].ToString();
It's always display me error for Session["ixCardType"] (error message: Object reference not set to an instance of an object). Anyway I can check the session before go to the .ToString() ??
Something as simple as an 'if' should work.
if(Session["ixCardType"] != null)
ixCardType.SelectedValue = Session["ixCardType"].ToString();
Or something like this if you want the empty string when the session value is null:
ixCardType.SelectedValue = Session["ixCardType"] == null? "" : Session["ixCardType"].ToString();
Cast the object using the as operator, which returns null if the value fails to cast to the desired class type, or if it's null itself.
string value = Session["ixCardType"] as string;
if (String.IsNullOrEmpty(value))
{
// null or empty
}
You can assign the result to a variable, and test it for null/empty prior to calling ToString():
var cardType = Session["ixCardType"];
if (cardType != null)
{
ixCardType.SelectedValue = cardType.ToString();
}

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") ?? "") : "";

Linq to sql: properties of properties that may be null

Simple LINQ query:
from transport in db.Transports
select new
{
Current = transport.CurrentLocation,
CurrentCarriers = transport.CurrentLocation.Carriers,
};
Problem: CurrentLocation may be null. If it is, executing this query throws a NullReference. I tried adding a check like
transport.CurrentLocation == null ? null : transport.CurrentLocation.Carriers
but Linq to sql does not seem to be able to parse that.
Any nice solutions that do not involve sending an extra query for each transport?
I normally just use 'let'.
from x in Foo
let y = x.Bar
where y != null
select y.Baz;
UPDATE:
I think the ?? operator does translate to SQL.
If the foreign key on Transports is nullable, you'll have to check that column for null before you can try and get the CurrentLocation object.
You could do something like this:
CurrentLocation = transport.currentLocationId != null ? transport.CurrentLocation : null;
Just do (you where using the wrong property):
transport.CurrentLocation == null ? null : transport.CurrentLocation.Carriers
Update 1: That is weird, I have used some pretty complex queries and didn't face that issue. I just checked one, don't think it matters, but mine had the check inverted:
transport.CurrentLocation != null ? transport.CurrentLocation.Carriers : null;
Can you post the complete query you tried that gives you the parse exception?

Categories