Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. Another reason I don't like LINQ

Another reason I don't like LINQ

Scheduled Pinned Locked Moved The Lounge
csharplinqdebugginghelpquestion
41 Posts 19 Posters 3 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • H honey the codewitch

    Here's my error

    System.ArgumentNullException: 'Value cannot be null.
    Parameter name: values'

    ... for this mess:

    Columns.AddRange(obj.GetType().GetGenericArguments().FirstOrDefault()?.GetProperties().Where(p =>
    {
    return p.GetCustomAttributes(true).OfType().FirstOrDefault()?.Browsable ?? DefaultBrowsableState;
    }).Select(p =>
    {
    return new ColumnHeader()
    {
    Name = p.Name,
    Text = p.GetCustomAttributes(true).OfType().FirstOrDefault()?.DisplayName ?? p.Name
    };
    }).ToArray());

    The thing is, I know what it's trying to do, and the code makes sense to me even though I didn't write it. The LINQ isn't really that bad here. But the error message is just awful. I don't even know where to begin. Time to hand roll the same statement LINQless so I can debug it. So consider this my part 2 in why LINQ is for the birds.

    Real programmers use butterflies

    C Offline
    C Offline
    charlieg
    wrote on last edited by
    #30

    is that custom generated? because if you had to write that -"their's your sign"

    Charlie Gilley <italic>Stuck in a dysfunctional matrix from which I must escape... "Where liberty dwells, there is my country." B. Franklin, 1783 “They who can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety.” BF, 1759

    1 Reply Last reply
    0
    • M Matthew Dennis

      I find that adding line breaks makes it a lot easier to read. Remember, you are writing for the next person to touch the code, not the computer. It is missing some Elvis operators, before the Where, the Select, and the ToArray, along with providing a value if the null propagates to the end. Also, you don't need the ToArray() as AddRange takes an IEnumerable<T>.

      Columns
      .AddRange(
      obj.GetType()
      .GetGenericArguments()
      .FirstOrDefault()?.GetProperties()

      // need the Elvis operator 
      ?.Where(p =>
      {
          return p.GetCustomAttributes(true)
                  .OfType()
                  .FirstOrDefault()?.Browsable ?? DefaultBrowsableState;
      })
      
      // need the Elvis operator 
      ?.Select(p =>
      {
          return new ColumnHeader()
          {
              Name = p.Name,
              Text = p.GetCustomAttributes(true)
                      .OfType().FirstOrDefault()?.DisplayName ?? p.Name
          };
      })
      
      // don't need ToArray(), but need to provide a non-null value for AddRange()
      ?? Array.Empty()
      

      );

      "Time flies like an arrow. Fruit flies like a banana."

      Richard DeemingR Online
      Richard DeemingR Online
      Richard Deeming
      wrote on last edited by
      #31

      Matthew Dennis wrote:

      It is missing some Elvis operators

      It's not. If the FirstOrDefault returns null, the GetProperties and subsequent calls won't execute. If it returns non-null, GetProperties will never return null:

      Type.GetProperties Method (System) | Microsoft Docs[^]:

      Returns An array of PropertyInfo objects representing all public properties of the current Type. -or- An empty array of type PropertyInfo, if the current Type does not have public properties.

      Similarly, Where will never return null. If the input sequence is null, it will throw an exception. If the input sequence is empty, or there are no matching elements, it will return an empty sequence. And the same applies to Select - it will either throw an exception, or return a non-null sequence.


      "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

      "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

      M 1 Reply Last reply
      0
      • R Ryan Peden

        A couple of possibly interesting bits of feedback, assuming that code comes from here: - Adding it to a WinForms app created with .NET Core 3.1 or .NET 5 and turning on nullable reference types finds 17 potential accidental nulls in the code from that SO post. But the Columns.AddRange call itself isn't one of them because WinForms wasn't built with NRT enabled. So the compiler decides it can't say one way or another if passing a null values argument to AddRange is okay. - Resharper catches the potential error whether you're using .NET Core/.NET 5 or .NET Framework. It even suggests a fix. The static analysis it's doing must look at AddRange and notice that the first thing that method does is throw an exception if values is null.

        Richard DeemingR Online
        Richard DeemingR Online
        Richard Deeming
        wrote on last edited by
        #32

        Ryan Peden wrote:

        The static analysis it's doing must look at AddRange and notice that the first thing that method does is throw an exception if values is null.

        I suspect it's more likely that it has "external annotations" for the type in question. External Annotations—ReSharper[^] R# is already slow enough; if it had to do static analysis on every framework method you called, it would be completely unusable. :)


        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

        "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

        1 Reply Last reply
        0
        • M Marc Clifton

          p.GetCustomAttributes(true).OfType()

          I believe OfType<>() is returning a null.

          honey the codewitch wrote:

          The LINQ isn't really that bad here.

          Actually, it's rather horrific. Not to mention what looks like completely unnecessary and probably wrong FirstOrDefault() usage, the reflection usage which looks like it could be simplified, and other confusing things. And the probably useless ToArray().

          honey the codewitch wrote:

          even though I didn't write it

          Whew! ;)

          Latest Articles:
          Client-Side Type-Based Publisher/Subscriber, Exploring Synchronous, "Event-ed", and Worker Thread Subscriptions

          Richard DeemingR Online
          Richard DeemingR Online
          Richard Deeming
          wrote on last edited by
          #33

          Marc Clifton wrote:

          I believe OfType<>() is returning a null.

          Nope. :) OfType<T> will throw an exception if the input sequence is null. If the input sequence is empty, or doesn't contain any matching elements, it will return an empty sequence. It can never return null. Also, the elements within the returned sequence will never be null.


          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

          H 1 Reply Last reply
          0
          • H honey the codewitch

            I mean, yes. eventually. but it (as someone mentioned earlier but I forget who) reminds me of C++ template exceptions. The code and the exception couldn't seem more unrelated on the surface, and code that isn't communicative at face value is problematic, which is basically my point here. I have the same complaint about C++ templates and generic programming despite being in love with GP. I guess for me the power of GP outweighs the incomprehensibility of it but I just don't feel that way with LINQ.

            Real programmers use butterflies

            Richard DeemingR Online
            Richard DeemingR Online
            Richard Deeming
            wrote on last edited by
            #34

            Try taking a look at the stack trace from an async method (prior to .NET Core 2.1). :)


            "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

            "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

            H 1 Reply Last reply
            0
            • Richard DeemingR Richard Deeming

              Matthew Dennis wrote:

              It is missing some Elvis operators

              It's not. If the FirstOrDefault returns null, the GetProperties and subsequent calls won't execute. If it returns non-null, GetProperties will never return null:

              Type.GetProperties Method (System) | Microsoft Docs[^]:

              Returns An array of PropertyInfo objects representing all public properties of the current Type. -or- An empty array of type PropertyInfo, if the current Type does not have public properties.

              Similarly, Where will never return null. If the input sequence is null, it will throw an exception. If the input sequence is empty, or there are no matching elements, it will return an empty sequence. And the same applies to Select - it will either throw an exception, or return a non-null sequence.


              "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

              M Offline
              M Offline
              Matthew Dennis
              wrote on last edited by
              #35

              actually that is incorrect. Only the chain of conditional operators is short circuited so if you have the expression

              A()?.Bb()?.C().D()

              and A() returns null the B and C will not be executed but there will be an attempt to execute D on a null object. Its sort of like async. You need to go all the way down. [Member access operators and expressions - C# reference | Microsoft Docs](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and-)

              "Time flies like an arrow. Fruit flies like a banana."

              Richard DeemingR 1 Reply Last reply
              0
              • M Matthew Dennis

                actually that is incorrect. Only the chain of conditional operators is short circuited so if you have the expression

                A()?.Bb()?.C().D()

                and A() returns null the B and C will not be executed but there will be an attempt to execute D on a null object. Its sort of like async. You need to go all the way down. [Member access operators and expressions - C# reference | Microsoft Docs](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and-)

                "Time flies like an arrow. Fruit flies like a banana."

                Richard DeemingR Online
                Richard DeemingR Online
                Richard Deeming
                wrote on last edited by
                #36

                I'm not convinced. :)

                static Foo A() => null;

                public class Foo
                {
                public Foo B() => null;
                public Foo C() => null;
                public Foo D() => null;
                }

                ...

                Foo result = A()?.B().C().D(); // result == null; no exception thrown.

                Null conditional operator | C# Online Compiler | .NET Fiddle[^]


                "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                M 1 Reply Last reply
                0
                • Richard DeemingR Richard Deeming

                  Try taking a look at the stack trace from an async method (prior to .NET Core 2.1). :)


                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                  H Offline
                  H Offline
                  honey the codewitch
                  wrote on last edited by
                  #37

                  Yeah, those were always fun. Sometimes - when the code flow was complicated - I used to prototype using blocking calls just so I could debug the logic, and then slowly roll in the asynchronous methods (BeginWrite, etc) until it stopped working. :sigh:

                  Real programmers use butterflies

                  1 Reply Last reply
                  0
                  • Richard DeemingR Richard Deeming

                    Marc Clifton wrote:

                    I believe OfType<>() is returning a null.

                    Nope. :) OfType<T> will throw an exception if the input sequence is null. If the input sequence is empty, or doesn't contain any matching elements, it will return an empty sequence. It can never return null. Also, the elements within the returned sequence will never be null.


                    "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                    H Offline
                    H Offline
                    honey the codewitch
                    wrote on last edited by
                    #38

                    This is illustrative of the point of my OP. If the error was clearer there would have been no confusion here.

                    Real programmers use butterflies

                    1 Reply Last reply
                    0
                    • R Ryan Peden

                      A couple of possibly interesting bits of feedback, assuming that code comes from here: - Adding it to a WinForms app created with .NET Core 3.1 or .NET 5 and turning on nullable reference types finds 17 potential accidental nulls in the code from that SO post. But the Columns.AddRange call itself isn't one of them because WinForms wasn't built with NRT enabled. So the compiler decides it can't say one way or another if passing a null values argument to AddRange is okay. - Resharper catches the potential error whether you're using .NET Core/.NET 5 or .NET Framework. It even suggests a fix. The static analysis it's doing must look at AddRange and notice that the first thing that method does is throw an exception if values is null.

                      H Offline
                      H Offline
                      honey the codewitch
                      wrote on last edited by
                      #39

                      That certainly makes using LINQ a bit nicer.

                      Real programmers use butterflies

                      1 Reply Last reply
                      0
                      • Richard DeemingR Richard Deeming

                        I'm not convinced. :)

                        static Foo A() => null;

                        public class Foo
                        {
                        public Foo B() => null;
                        public Foo C() => null;
                        public Foo D() => null;
                        }

                        ...

                        Foo result = A()?.B().C().D(); // result == null; no exception thrown.

                        Null conditional operator | C# Online Compiler | .NET Fiddle[^]


                        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                        M Offline
                        M Offline
                        Matthew Dennis
                        wrote on last edited by
                        #40

                        You may be correct. The documentation is a little vague on the extent of the short circuiting.

                        "Time flies like an arrow. Fruit flies like a banana."

                        M 1 Reply Last reply
                        0
                        • M Matthew Dennis

                          You may be correct. The documentation is a little vague on the extent of the short circuiting.

                          "Time flies like an arrow. Fruit flies like a banana."

                          M Offline
                          M Offline
                          Matthew Dennis
                          wrote on last edited by
                          #41

                          I checked this out and it appears that as long as the null occurs before a ?. or ?[] operator, the rest of the chain is short circuited and has a value of NULL. You learn something everyday. Thanks

                          "Time flies like an arrow. Fruit flies like a banana."

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups