Search code examples
c#linqxelement

Linq Xelement and Class


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


Solution

  • 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