-3

I have the following code:

var te = doc.Descendants("TESTID").Where(x=> (string)x.Attribute("TESTIDNumber")= finalstr).FirstOrDefault();

In the case te is null, then the following gives an exeption:

var ignorete = doc.Descendants("IgnoreTESTID").Where(x=> (string)x.Attribute("TESTIDNumber")== te.FirstAttribute.Value.toString();

The exception is : Object not set to an instance of the Object

How do I make ignorete to null if te goes null ?

user726720
  • 1,127
  • 7
  • 25
  • 59

2 Answers2

2

You just need a guard clause:

public string GetIgnorete()
{
    var te = doc.Descendants("TESTID").Where(x=>  (string)x.Attribute("TESTIDNumber") == finalstr).FirstOrDefault();
    if ( te == null ) return null;
    return doc.Descendants("IgnoreTESTID").Where(x=> (string)x.Attribute("TESTIDNumber") == te.FirstAttribute.Value.toString();
}

Or you could just use the conditional operator:

var ignorete = (te == null) ? null : doc.Descendants("IgnoreTESTID").Where( x => etc –

Note: I took the liberty of changing your = to a ==. The latter is the equality operator which results in a Boolean based on the comparison. The former is the assignment operator whose result is the value of the assignment.

John Wu
  • 50,556
  • 8
  • 44
  • 80
  • `(string)x.Attribute("TESTIDNumber")= te.FirstAttribute.Value.toString();`? – Liam Apr 27 '18 at 08:48
  • The code in this answer will not work. It's using an asignment operator `=` instead of a comparison operator `==` and it's missing a brace `.Where(x=> (string)x.Attribute("TESTIDNumber")= te.FirstAttribute.Value.toString();` – Liam Apr 27 '18 at 10:10
0

You can't, because a var must be instatiated so that C# can assign a type. You cannot create a var object and set it to null.

In this case, you would need to declare it as whatever object type doc.Descendants returns. I've declared as a generic object below:

object ignorete = te != null ? doc.Descendants("IgnoreTESTID").Where(x=> (string)x.Attribute("TESTIDNumber")= te.FirstAttribute.Value.toString()) : null;
ataraxia
  • 995
  • 13
  • 31