Is it unreasonable to expect Any() *not* to throw a null reference exception?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
2
down vote

favorite












When you create an extension method you can, of course, call it on null.But, unlike an instance method call, calling it on null doesn't have to throw a NullReferenceException -> you have to check and throw it manually.



For the implementation of the Linq extension method Any() Microsoft decided that they should throw a NullReferenceException (https://github.com/dotnet/corefx/blob/master/src/System.Linq/src/System/Linq/AnyAll.cs).



It irks me to have to write if( myCollection != null && myCollection.Any() )



Am I wrong, as a client of this code, to expect that e.g. ((int)null).Any() should return false?










share|improve this question







New contributor




thisextendsthat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.



















  • This is too opinionated for this site, however I too am constantly annoyed about checking for null when I treat a null collection and empty collection exactly the same: Don't do anything with it. However, this breaks down when a null pointer is meaningful versus an empty collection (hide search results if null versus "Your search returned no results").
    – Greg Burghardt
    8 mins ago
















up vote
2
down vote

favorite












When you create an extension method you can, of course, call it on null.But, unlike an instance method call, calling it on null doesn't have to throw a NullReferenceException -> you have to check and throw it manually.



For the implementation of the Linq extension method Any() Microsoft decided that they should throw a NullReferenceException (https://github.com/dotnet/corefx/blob/master/src/System.Linq/src/System/Linq/AnyAll.cs).



It irks me to have to write if( myCollection != null && myCollection.Any() )



Am I wrong, as a client of this code, to expect that e.g. ((int)null).Any() should return false?










share|improve this question







New contributor




thisextendsthat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.



















  • This is too opinionated for this site, however I too am constantly annoyed about checking for null when I treat a null collection and empty collection exactly the same: Don't do anything with it. However, this breaks down when a null pointer is meaningful versus an empty collection (hide search results if null versus "Your search returned no results").
    – Greg Burghardt
    8 mins ago












up vote
2
down vote

favorite









up vote
2
down vote

favorite











When you create an extension method you can, of course, call it on null.But, unlike an instance method call, calling it on null doesn't have to throw a NullReferenceException -> you have to check and throw it manually.



For the implementation of the Linq extension method Any() Microsoft decided that they should throw a NullReferenceException (https://github.com/dotnet/corefx/blob/master/src/System.Linq/src/System/Linq/AnyAll.cs).



It irks me to have to write if( myCollection != null && myCollection.Any() )



Am I wrong, as a client of this code, to expect that e.g. ((int)null).Any() should return false?










share|improve this question







New contributor




thisextendsthat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











When you create an extension method you can, of course, call it on null.But, unlike an instance method call, calling it on null doesn't have to throw a NullReferenceException -> you have to check and throw it manually.



For the implementation of the Linq extension method Any() Microsoft decided that they should throw a NullReferenceException (https://github.com/dotnet/corefx/blob/master/src/System.Linq/src/System/Linq/AnyAll.cs).



It irks me to have to write if( myCollection != null && myCollection.Any() )



Am I wrong, as a client of this code, to expect that e.g. ((int)null).Any() should return false?







c# .net linq extension-method






share|improve this question







New contributor




thisextendsthat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question







New contributor




thisextendsthat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question






New contributor




thisextendsthat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 2 hours ago









thisextendsthat

1172




1172




New contributor




thisextendsthat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





thisextendsthat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






thisextendsthat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











  • This is too opinionated for this site, however I too am constantly annoyed about checking for null when I treat a null collection and empty collection exactly the same: Don't do anything with it. However, this breaks down when a null pointer is meaningful versus an empty collection (hide search results if null versus "Your search returned no results").
    – Greg Burghardt
    8 mins ago
















  • This is too opinionated for this site, however I too am constantly annoyed about checking for null when I treat a null collection and empty collection exactly the same: Don't do anything with it. However, this breaks down when a null pointer is meaningful versus an empty collection (hide search results if null versus "Your search returned no results").
    – Greg Burghardt
    8 mins ago















This is too opinionated for this site, however I too am constantly annoyed about checking for null when I treat a null collection and empty collection exactly the same: Don't do anything with it. However, this breaks down when a null pointer is meaningful versus an empty collection (hide search results if null versus "Your search returned no results").
– Greg Burghardt
8 mins ago




This is too opinionated for this site, however I too am constantly annoyed about checking for null when I treat a null collection and empty collection exactly the same: Don't do anything with it. However, this breaks down when a null pointer is meaningful versus an empty collection (hide search results if null versus "Your search returned no results").
– Greg Burghardt
8 mins ago










4 Answers
4






active

oldest

votes

















up vote
5
down vote













First off, it appears that that source code will throw ArgumentNullException, not NullReferenceException.



Having said that, in many cases you already know that your collection is not null, because this code is only called from code that knows that the collection already exists, so you won't have to put the null check in there very often. But if you don't know that it exists, then it does make sense to check before calling Any() on it.




Am I wrong, as a client of this code, to expect that e.g. ((int)null).Any() should return false?




Yes. The question that Any() answers is "does this collection contain any elements?" If this collection does not exist, then the question itself is nonsensical; it can neither contain nor not-contain anything, because it doesn't exist.






share|improve this answer



























    up vote
    3
    down vote













    I have a bag with five potatoes in it. Are there .Any() potatoes in the bag?



    "Yes," you say. <= true



    I take all of the potatoes out and eat them. Are there .Any() potatoes in the bag?



    "No," you say. <= false



    I completely incinerate the bag in a fire. Are there .Any() potatoes in the bag now?



    "There is no bag." <= ArgumentNullException






    share|improve this answer
















    • 1




      Love the illustration! +1 Still annoys me to do a null check when I don't care if the bag was incinerated though. I'm totally including this extension method in all future projects: IEnumerable<T>.IsIncineratedOrEmpty()
      – Greg Burghardt
      12 mins ago

















    up vote
    0
    down vote













    Null means missing information, not no elements.



    You might consider more broadly avoiding null -- for example, use one of the built-in empty enumerables to represent a collection with no elements instead of null.



    If you are returning null in some circumstances, you might change that to return the empty collection.  (Otherwise, if you're finding null's returned by library methods (not yours), that's unfortunate, and I would wrap them to normalize.)  See also
    https://stackoverflow.com/questions/1191919/what-does-linq-return-when-the-results-are-empty






    share|improve this answer




















    • That null doesn't mean no elements is a matter of using a sensible convention. Just think about native OLESTRINGS, where it actually does mean that.
      – Deduplicator
      1 hour ago











    • @Deduplicator, are you talking about Microsoft's Object Linking and Embedding perchance? If you are let's recall that OLE is from the '90s! Looking more currently, many modern languages (C#,Java,Swift) are providing facilities to eliminate/eradicate uses of null.
      – Erik Eidt
      54 mins ago


















    up vote
    0
    down vote














    Am I wrong, as a client of this code, to expect that e.g. ((int)null).Any() should return false?




    Yes, simply because you're in C# and that behavior is well defined and documented.



    If you were making your own library, or if you were using a different language with different exception culture then it would be more reasonable to expect false.



    Personally I feel as though that is a safer approach that makes your program more robust, but it's debatable at least.






    share|improve this answer




















      Your Answer







      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "131"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      convertImagesToLinks: false,
      noModals: false,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );






      thisextendsthat is a new contributor. Be nice, and check out our Code of Conduct.









       

      draft saved


      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsoftwareengineering.stackexchange.com%2fquestions%2f378612%2fis-it-unreasonable-to-expect-any-not-to-throw-a-null-reference-exception%23new-answer', 'question_page');

      );

      Post as a guest






























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      5
      down vote













      First off, it appears that that source code will throw ArgumentNullException, not NullReferenceException.



      Having said that, in many cases you already know that your collection is not null, because this code is only called from code that knows that the collection already exists, so you won't have to put the null check in there very often. But if you don't know that it exists, then it does make sense to check before calling Any() on it.




      Am I wrong, as a client of this code, to expect that e.g. ((int)null).Any() should return false?




      Yes. The question that Any() answers is "does this collection contain any elements?" If this collection does not exist, then the question itself is nonsensical; it can neither contain nor not-contain anything, because it doesn't exist.






      share|improve this answer
























        up vote
        5
        down vote













        First off, it appears that that source code will throw ArgumentNullException, not NullReferenceException.



        Having said that, in many cases you already know that your collection is not null, because this code is only called from code that knows that the collection already exists, so you won't have to put the null check in there very often. But if you don't know that it exists, then it does make sense to check before calling Any() on it.




        Am I wrong, as a client of this code, to expect that e.g. ((int)null).Any() should return false?




        Yes. The question that Any() answers is "does this collection contain any elements?" If this collection does not exist, then the question itself is nonsensical; it can neither contain nor not-contain anything, because it doesn't exist.






        share|improve this answer






















          up vote
          5
          down vote










          up vote
          5
          down vote









          First off, it appears that that source code will throw ArgumentNullException, not NullReferenceException.



          Having said that, in many cases you already know that your collection is not null, because this code is only called from code that knows that the collection already exists, so you won't have to put the null check in there very often. But if you don't know that it exists, then it does make sense to check before calling Any() on it.




          Am I wrong, as a client of this code, to expect that e.g. ((int)null).Any() should return false?




          Yes. The question that Any() answers is "does this collection contain any elements?" If this collection does not exist, then the question itself is nonsensical; it can neither contain nor not-contain anything, because it doesn't exist.






          share|improve this answer












          First off, it appears that that source code will throw ArgumentNullException, not NullReferenceException.



          Having said that, in many cases you already know that your collection is not null, because this code is only called from code that knows that the collection already exists, so you won't have to put the null check in there very often. But if you don't know that it exists, then it does make sense to check before calling Any() on it.




          Am I wrong, as a client of this code, to expect that e.g. ((int)null).Any() should return false?




          Yes. The question that Any() answers is "does this collection contain any elements?" If this collection does not exist, then the question itself is nonsensical; it can neither contain nor not-contain anything, because it doesn't exist.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 1 hour ago









          Mason Wheeler

          72.9k18206294




          72.9k18206294






















              up vote
              3
              down vote













              I have a bag with five potatoes in it. Are there .Any() potatoes in the bag?



              "Yes," you say. <= true



              I take all of the potatoes out and eat them. Are there .Any() potatoes in the bag?



              "No," you say. <= false



              I completely incinerate the bag in a fire. Are there .Any() potatoes in the bag now?



              "There is no bag." <= ArgumentNullException






              share|improve this answer
















              • 1




                Love the illustration! +1 Still annoys me to do a null check when I don't care if the bag was incinerated though. I'm totally including this extension method in all future projects: IEnumerable<T>.IsIncineratedOrEmpty()
                – Greg Burghardt
                12 mins ago














              up vote
              3
              down vote













              I have a bag with five potatoes in it. Are there .Any() potatoes in the bag?



              "Yes," you say. <= true



              I take all of the potatoes out and eat them. Are there .Any() potatoes in the bag?



              "No," you say. <= false



              I completely incinerate the bag in a fire. Are there .Any() potatoes in the bag now?



              "There is no bag." <= ArgumentNullException






              share|improve this answer
















              • 1




                Love the illustration! +1 Still annoys me to do a null check when I don't care if the bag was incinerated though. I'm totally including this extension method in all future projects: IEnumerable<T>.IsIncineratedOrEmpty()
                – Greg Burghardt
                12 mins ago












              up vote
              3
              down vote










              up vote
              3
              down vote









              I have a bag with five potatoes in it. Are there .Any() potatoes in the bag?



              "Yes," you say. <= true



              I take all of the potatoes out and eat them. Are there .Any() potatoes in the bag?



              "No," you say. <= false



              I completely incinerate the bag in a fire. Are there .Any() potatoes in the bag now?



              "There is no bag." <= ArgumentNullException






              share|improve this answer












              I have a bag with five potatoes in it. Are there .Any() potatoes in the bag?



              "Yes," you say. <= true



              I take all of the potatoes out and eat them. Are there .Any() potatoes in the bag?



              "No," you say. <= false



              I completely incinerate the bag in a fire. Are there .Any() potatoes in the bag now?



              "There is no bag." <= ArgumentNullException







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered 40 mins ago









              Dan Wilson

              5208




              5208







              • 1




                Love the illustration! +1 Still annoys me to do a null check when I don't care if the bag was incinerated though. I'm totally including this extension method in all future projects: IEnumerable<T>.IsIncineratedOrEmpty()
                – Greg Burghardt
                12 mins ago












              • 1




                Love the illustration! +1 Still annoys me to do a null check when I don't care if the bag was incinerated though. I'm totally including this extension method in all future projects: IEnumerable<T>.IsIncineratedOrEmpty()
                – Greg Burghardt
                12 mins ago







              1




              1




              Love the illustration! +1 Still annoys me to do a null check when I don't care if the bag was incinerated though. I'm totally including this extension method in all future projects: IEnumerable<T>.IsIncineratedOrEmpty()
              – Greg Burghardt
              12 mins ago




              Love the illustration! +1 Still annoys me to do a null check when I don't care if the bag was incinerated though. I'm totally including this extension method in all future projects: IEnumerable<T>.IsIncineratedOrEmpty()
              – Greg Burghardt
              12 mins ago










              up vote
              0
              down vote













              Null means missing information, not no elements.



              You might consider more broadly avoiding null -- for example, use one of the built-in empty enumerables to represent a collection with no elements instead of null.



              If you are returning null in some circumstances, you might change that to return the empty collection.  (Otherwise, if you're finding null's returned by library methods (not yours), that's unfortunate, and I would wrap them to normalize.)  See also
              https://stackoverflow.com/questions/1191919/what-does-linq-return-when-the-results-are-empty






              share|improve this answer




















              • That null doesn't mean no elements is a matter of using a sensible convention. Just think about native OLESTRINGS, where it actually does mean that.
                – Deduplicator
                1 hour ago











              • @Deduplicator, are you talking about Microsoft's Object Linking and Embedding perchance? If you are let's recall that OLE is from the '90s! Looking more currently, many modern languages (C#,Java,Swift) are providing facilities to eliminate/eradicate uses of null.
                – Erik Eidt
                54 mins ago















              up vote
              0
              down vote













              Null means missing information, not no elements.



              You might consider more broadly avoiding null -- for example, use one of the built-in empty enumerables to represent a collection with no elements instead of null.



              If you are returning null in some circumstances, you might change that to return the empty collection.  (Otherwise, if you're finding null's returned by library methods (not yours), that's unfortunate, and I would wrap them to normalize.)  See also
              https://stackoverflow.com/questions/1191919/what-does-linq-return-when-the-results-are-empty






              share|improve this answer




















              • That null doesn't mean no elements is a matter of using a sensible convention. Just think about native OLESTRINGS, where it actually does mean that.
                – Deduplicator
                1 hour ago











              • @Deduplicator, are you talking about Microsoft's Object Linking and Embedding perchance? If you are let's recall that OLE is from the '90s! Looking more currently, many modern languages (C#,Java,Swift) are providing facilities to eliminate/eradicate uses of null.
                – Erik Eidt
                54 mins ago













              up vote
              0
              down vote










              up vote
              0
              down vote









              Null means missing information, not no elements.



              You might consider more broadly avoiding null -- for example, use one of the built-in empty enumerables to represent a collection with no elements instead of null.



              If you are returning null in some circumstances, you might change that to return the empty collection.  (Otherwise, if you're finding null's returned by library methods (not yours), that's unfortunate, and I would wrap them to normalize.)  See also
              https://stackoverflow.com/questions/1191919/what-does-linq-return-when-the-results-are-empty






              share|improve this answer












              Null means missing information, not no elements.



              You might consider more broadly avoiding null -- for example, use one of the built-in empty enumerables to represent a collection with no elements instead of null.



              If you are returning null in some circumstances, you might change that to return the empty collection.  (Otherwise, if you're finding null's returned by library methods (not yours), that's unfortunate, and I would wrap them to normalize.)  See also
              https://stackoverflow.com/questions/1191919/what-does-linq-return-when-the-results-are-empty







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered 1 hour ago









              Erik Eidt

              20.4k33051




              20.4k33051











              • That null doesn't mean no elements is a matter of using a sensible convention. Just think about native OLESTRINGS, where it actually does mean that.
                – Deduplicator
                1 hour ago











              • @Deduplicator, are you talking about Microsoft's Object Linking and Embedding perchance? If you are let's recall that OLE is from the '90s! Looking more currently, many modern languages (C#,Java,Swift) are providing facilities to eliminate/eradicate uses of null.
                – Erik Eidt
                54 mins ago

















              • That null doesn't mean no elements is a matter of using a sensible convention. Just think about native OLESTRINGS, where it actually does mean that.
                – Deduplicator
                1 hour ago











              • @Deduplicator, are you talking about Microsoft's Object Linking and Embedding perchance? If you are let's recall that OLE is from the '90s! Looking more currently, many modern languages (C#,Java,Swift) are providing facilities to eliminate/eradicate uses of null.
                – Erik Eidt
                54 mins ago
















              That null doesn't mean no elements is a matter of using a sensible convention. Just think about native OLESTRINGS, where it actually does mean that.
              – Deduplicator
              1 hour ago





              That null doesn't mean no elements is a matter of using a sensible convention. Just think about native OLESTRINGS, where it actually does mean that.
              – Deduplicator
              1 hour ago













              @Deduplicator, are you talking about Microsoft's Object Linking and Embedding perchance? If you are let's recall that OLE is from the '90s! Looking more currently, many modern languages (C#,Java,Swift) are providing facilities to eliminate/eradicate uses of null.
              – Erik Eidt
              54 mins ago





              @Deduplicator, are you talking about Microsoft's Object Linking and Embedding perchance? If you are let's recall that OLE is from the '90s! Looking more currently, many modern languages (C#,Java,Swift) are providing facilities to eliminate/eradicate uses of null.
              – Erik Eidt
              54 mins ago











              up vote
              0
              down vote














              Am I wrong, as a client of this code, to expect that e.g. ((int)null).Any() should return false?




              Yes, simply because you're in C# and that behavior is well defined and documented.



              If you were making your own library, or if you were using a different language with different exception culture then it would be more reasonable to expect false.



              Personally I feel as though that is a safer approach that makes your program more robust, but it's debatable at least.






              share|improve this answer
























                up vote
                0
                down vote














                Am I wrong, as a client of this code, to expect that e.g. ((int)null).Any() should return false?




                Yes, simply because you're in C# and that behavior is well defined and documented.



                If you were making your own library, or if you were using a different language with different exception culture then it would be more reasonable to expect false.



                Personally I feel as though that is a safer approach that makes your program more robust, but it's debatable at least.






                share|improve this answer






















                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote










                  Am I wrong, as a client of this code, to expect that e.g. ((int)null).Any() should return false?




                  Yes, simply because you're in C# and that behavior is well defined and documented.



                  If you were making your own library, or if you were using a different language with different exception culture then it would be more reasonable to expect false.



                  Personally I feel as though that is a safer approach that makes your program more robust, but it's debatable at least.






                  share|improve this answer













                  Am I wrong, as a client of this code, to expect that e.g. ((int)null).Any() should return false?




                  Yes, simply because you're in C# and that behavior is well defined and documented.



                  If you were making your own library, or if you were using a different language with different exception culture then it would be more reasonable to expect false.



                  Personally I feel as though that is a safer approach that makes your program more robust, but it's debatable at least.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 27 mins ago









                  Telastyn

                  90.1k24203310




                  90.1k24203310




















                      thisextendsthat is a new contributor. Be nice, and check out our Code of Conduct.









                       

                      draft saved


                      draft discarded


















                      thisextendsthat is a new contributor. Be nice, and check out our Code of Conduct.












                      thisextendsthat is a new contributor. Be nice, and check out our Code of Conduct.











                      thisextendsthat is a new contributor. Be nice, and check out our Code of Conduct.













                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsoftwareengineering.stackexchange.com%2fquestions%2f378612%2fis-it-unreasonable-to-expect-any-not-to-throw-a-null-reference-exception%23new-answer', 'question_page');

                      );

                      Post as a guest













































































                      Comments

                      Popular posts from this blog

                      Long meetings (6-7 hours a day): Being “babysat” by supervisor

                      Is the Concept of Multiple Fantasy Races Scientifically Flawed? [closed]

                      Confectionery