Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign and check for a null value at the same time?

Tags:

c#

I have the following scenario:

if(xml.Descendants(ns + "Children").FirstOrDefault() != null)
{
    XElement children = xml.Descendants(ns + "Children").FirstOrDefault();
}

Is there a way I can check for null and assign the value at the same time instead of having to search for the value twice, something similar to:

//Not sure if this is correct.
if (XElement children = xml.Descendants(ns + "Children").FirstOrDefault() != null)
{

}
like image 880
Xaisoft Avatar asked Jun 15 '12 13:06

Xaisoft


People also ask

How do you check for null?

The simplest way to check for null is to know that null evaluates to false in conditionals or if coerced to a boolean value: Of course, that does not differentiate null from the other falsy values. Next, I explore using the == or === equality operators to check for null.

How do you set a value if it is null in Java?

In Java, null is a literal. It is mainly used to assign a null value to a variable. A null value is possible for a string, object, or date and time, etc. We cannot assign a null value to the primitive data types such as int, float, etc.

Is string empty or null C#?

In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.

What does if NULL return?

Returns a result if the input is null, otherwise, returns the input.


3 Answers

A variable assignment also returns the value. So the syntax in the form of the following will do:

SomeType someVariable;
if ((someVariable = valueToAssign) != null)
{
    // valueToAssign was not null
}

In your case:

XElement children;

if ((children = xml.Descendants(ns + "Children").FirstOrDefault()) != null)
{

}
like image 193
CodeCaster Avatar answered Sep 30 '22 18:09

CodeCaster


I would do it this way:

XElement children = xml.Descendants(ns + "Children").FirstOrDefault();
if(children != null)
{
    //use children
}
like image 37
Tim S. Avatar answered Sep 30 '22 18:09

Tim S.


You could just do

XElement children = xml.Descendants(ns + "Children").FirstOrDefault();

and then check for null

if (children != null) {...}
like image 35
Claudio Redi Avatar answered Sep 30 '22 18:09

Claudio Redi