-1

So, let me explain my trouble.

I get a project which was develop by another guy, and he leaved the firm. Now i have to update the program but something going wrong when i import the solution.

Let see the code:

  ListeDeTypeDePoste = (from e in xml.Descendants("profil")
                              select new TypeDePoste()
                              {
                                  Nom = e.Element("name").Value,
                                  Chaines = (from c in e.Elements("Chaine")
                                             select new Chaine()
                                             {
                                                 Code = c.Element("Code")?.Value,
                                                 Type = c.Element("Type")?.Value,
                                                 Nom = c.Element("Nom")?.Value,
                                                 OU = c.Element("OU")?.Value
                                             }).ToList()
                              }).ToList<TypeDePoste>();

The trouble is on the .?Value for each properties in a Chaine Class, when i debug i can even debug the solution and if i remove them i got a NullReferenceException. With this code the previous realese .exe worked like a charm

2 Answers2

1

You can use the operator ?. only in C# 6.0.

This is null-propagation operator. If you don't want to use it, you can change your assignment to properties of Chaine class:

select new Chaine()
{
    Code = (c.Element("Code") == null) ? null : c.Element("Code").Value,
    Type = (c.Element("Type") == null) ? null : c.Element("Type").Value,
    Nom = (c.Element("Nom") == null) ? null : c.Element("Nom").Value,
    OU = (c.Element("OU") == null) ? null : c.Element("OU").Value
}).ToList()

If you delete ? in this operator the assignment will crash because you try to get value of null.

If c.Element("Code") is null then this code will simply assign null to Code:

Code = c.Element("Code")?.Value;

But without ?:

Code = c.Element("Code").Value; //app will throw an exception because c.Element("Code") is null
Roman
  • 11,966
  • 10
  • 38
  • 47
1

This is because the Element calls in that code are sometimes returning null, because an element with the given name doesn't exist at that location in the XML document you're processing.

The ?. (null-conditional) operator tests for this, returning null in such a scenario.

If you use . instead (without adding your own null check), then a NullReferenceException will be thrown in such a scenario. This is by-design in C#.

The null-conditional operator was introduced in C# 6, so to use it you'll need to install Visual Studio 2015.

Richard Ev
  • 52,939
  • 59
  • 191
  • 278