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. Other Discussions
  3. The Weird and The Wonderful
  4. Can you call a method on an object that is null?

Can you call a method on an object that is null?

Scheduled Pinned Locked Moved The Weird and The Wonderful
csharpquestion
11 Posts 10 Posters 0 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.
  • L Offline
    L Offline
    Lost User
    wrote on last edited by
    #1

    Apparently no, isnt't it? But run this code:

    class Program {

    static void Main(string\[\] args) {
        object o = null;
    
        Console.WriteLine(o.IsNull());
    }
    

    }

    public static class ExtensionMethods {

    public static bool IsNull(this object obj) {
        return (obj == null);
    }
    

    }

    If you expected it to throw a NullReferenceException (as I did), then you're in for a surprise. It actually prints true. Makes me wonder how extension methods are implemented internally. Something like a wrapper object over the null object? Any .NET experts here that can explain?

    OriginalGriffO A J F O 6 Replies Last reply
    0
    • L Lost User

      Apparently no, isnt't it? But run this code:

      class Program {

      static void Main(string\[\] args) {
          object o = null;
      
          Console.WriteLine(o.IsNull());
      }
      

      }

      public static class ExtensionMethods {

      public static bool IsNull(this object obj) {
          return (obj == null);
      }
      

      }

      If you expected it to throw a NullReferenceException (as I did), then you're in for a surprise. It actually prints true. Makes me wonder how extension methods are implemented internally. Something like a wrapper object over the null object? Any .NET experts here that can explain?

      OriginalGriffO Offline
      OriginalGriffO Offline
      OriginalGriff
      wrote on last edited by
      #2

      Extension methods are implemented as you would expect: as a call to a static method, with a parameter. So effectively, what you have written is:

      public static bool IsNull(object o)
      {
      return (o == null);
      }
      ...
      if (IsNull(null))
      {
      ...

      Which nobody would expect to throw a null reference. The extension method bit is just syntactic sugar. Looks odd though!

      Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water

      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
      "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

      L 1 Reply Last reply
      0
      • OriginalGriffO OriginalGriff

        Extension methods are implemented as you would expect: as a call to a static method, with a parameter. So effectively, what you have written is:

        public static bool IsNull(object o)
        {
        return (o == null);
        }
        ...
        if (IsNull(null))
        {
        ...

        Which nobody would expect to throw a null reference. The extension method bit is just syntactic sugar. Looks odd though!

        Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water

        L Offline
        L Offline
        Lost User
        wrote on last edited by
        #3

        Yes, I understand. But what intrigues me is the

        o.IsNull()

        syntax, the mental picture I get is that since o is null, any attempt to call a method/field would throw a NullReferenceException, replace IsNull() with ToString() and you'll know what I'm talking about.

        object.IsNull(o)

        would have made much sense.

        B 1 Reply Last reply
        0
        • L Lost User

          Apparently no, isnt't it? But run this code:

          class Program {

          static void Main(string\[\] args) {
              object o = null;
          
              Console.WriteLine(o.IsNull());
          }
          

          }

          public static class ExtensionMethods {

          public static bool IsNull(this object obj) {
              return (obj == null);
          }
          

          }

          If you expected it to throw a NullReferenceException (as I did), then you're in for a surprise. It actually prints true. Makes me wonder how extension methods are implemented internally. Something like a wrapper object over the null object? Any .NET experts here that can explain?

          A Offline
          A Offline
          Adriaan Davel
          wrote on last edited by
          #4

          I often use this as an 'exploit', can help make your code more readable in some cases. Sometimes I rather create an extension method than an instance method and do the null checking in the method instead of the calling procedure. (Not recommended as default pattern though) :)

          ____________________________________________________________ Be brave little warrior, be VERY brave

          1 Reply Last reply
          0
          • L Lost User

            Yes, I understand. But what intrigues me is the

            o.IsNull()

            syntax, the mental picture I get is that since o is null, any attempt to call a method/field would throw a NullReferenceException, replace IsNull() with ToString() and you'll know what I'm talking about.

            object.IsNull(o)

            would have made much sense.

            B Offline
            B Offline
            BobJanova
            wrote on last edited by
            #5

            The whole point of extension methods is to avoid having to make explicit static calls. I don't really like them because they're hiding what's actually going on, but on the other hand those Linq method trains on IEnumerable<T> (all extension methods obviously) are really convenient. I don't get the point of IsNull, though. o.IsNull() is more characters and less clear than o == null! (And although you can override == on a custom type so that does something different, anyone who overrides it in a way that makes o == null not do what you expect should be taken out and shot repeatedly.)

            B 1 Reply Last reply
            0
            • L Lost User

              Apparently no, isnt't it? But run this code:

              class Program {

              static void Main(string\[\] args) {
                  object o = null;
              
                  Console.WriteLine(o.IsNull());
              }
              

              }

              public static class ExtensionMethods {

              public static bool IsNull(this object obj) {
                  return (obj == null);
              }
              

              }

              If you expected it to throw a NullReferenceException (as I did), then you're in for a surprise. It actually prints true. Makes me wonder how extension methods are implemented internally. Something like a wrapper object over the null object? Any .NET experts here that can explain?

              J Offline
              J Offline
              J4amieC
              wrote on last edited by
              #6

              Ive taken huge advantage of this recently when using PerformanceCounters. You see I create performance counters if possible, but it's entirely expected that some developer machines might not yet have my PerformanceCounters and I didnt want my code to not work on their machines. Hence this Extension class

              public static class PerformanceCounterExtensions
              {
              public static void SafeIncrement(this PerformanceCounter counter)
              {
              if (counter != null)
              counter.Increment();
              }

                  public static void SafeDecrement(this PerformanceCounter counter)
                  {
                      if (counter != null)
                          counter.Decrement();
                  }
              
                  public static void SafeIncrementBy(this PerformanceCounter counter, long value)
                  {
                      if (counter != null)
                          counter.IncrementBy(value);
                  }
              
                  public static void SafeReset(this PerformanceCounter counter)
                  {
                      if (counter != null)
                          counter.RawValue = 0;
                  }
              }
              
              E 1 Reply Last reply
              0
              • L Lost User

                Apparently no, isnt't it? But run this code:

                class Program {

                static void Main(string\[\] args) {
                    object o = null;
                
                    Console.WriteLine(o.IsNull());
                }
                

                }

                public static class ExtensionMethods {

                public static bool IsNull(this object obj) {
                    return (obj == null);
                }
                

                }

                If you expected it to throw a NullReferenceException (as I did), then you're in for a surprise. It actually prints true. Makes me wonder how extension methods are implemented internally. Something like a wrapper object over the null object? Any .NET experts here that can explain?

                F Offline
                F Offline
                Florin Jurcovici
                wrote on last edited by
                #7

                You can, in C++. And you don't get an exception/runtime error until your program tries to touch data members - much deeper in the call stack than the actual call point. Which makes debugging a very funny thing ...

                1 Reply Last reply
                0
                • L Lost User

                  Apparently no, isnt't it? But run this code:

                  class Program {

                  static void Main(string\[\] args) {
                      object o = null;
                  
                      Console.WriteLine(o.IsNull());
                  }
                  

                  }

                  public static class ExtensionMethods {

                  public static bool IsNull(this object obj) {
                      return (obj == null);
                  }
                  

                  }

                  If you expected it to throw a NullReferenceException (as I did), then you're in for a surprise. It actually prints true. Makes me wonder how extension methods are implemented internally. Something like a wrapper object over the null object? Any .NET experts here that can explain?

                  O Offline
                  O Offline
                  onelopez
                  wrote on last edited by
                  #8

                  The compiler does not read an extension method as a method belonging to the instance object, instead it expands your code to something like:

                  Console.WriteLine(ExtensionMethods.IsNull(o));

                  Therefore, you do not get an exception.

                  1 Reply Last reply
                  0
                  • B BobJanova

                    The whole point of extension methods is to avoid having to make explicit static calls. I don't really like them because they're hiding what's actually going on, but on the other hand those Linq method trains on IEnumerable<T> (all extension methods obviously) are really convenient. I don't get the point of IsNull, though. o.IsNull() is more characters and less clear than o == null! (And although you can override == on a custom type so that does something different, anyone who overrides it in a way that makes o == null not do what you expect should be taken out and shot repeatedly.)

                    B Offline
                    B Offline
                    Brisingr Aerowing
                    wrote on last edited by
                    #9

                    Or be burned alive. In hot lava. Along with the code he wrote.

                    Bill Gates is a very rich man today... and do you want to know why? The answer is one word: versions. Dave Barry Read more at [BrainyQuote](http://www.brainyquote.com/quotes/topics topic_technology.html#yAfSEbrfumitrteO.99)[^]

                    1 Reply Last reply
                    0
                    • J J4amieC

                      Ive taken huge advantage of this recently when using PerformanceCounters. You see I create performance counters if possible, but it's entirely expected that some developer machines might not yet have my PerformanceCounters and I didnt want my code to not work on their machines. Hence this Extension class

                      public static class PerformanceCounterExtensions
                      {
                      public static void SafeIncrement(this PerformanceCounter counter)
                      {
                      if (counter != null)
                      counter.Increment();
                      }

                          public static void SafeDecrement(this PerformanceCounter counter)
                          {
                              if (counter != null)
                                  counter.Decrement();
                          }
                      
                          public static void SafeIncrementBy(this PerformanceCounter counter, long value)
                          {
                              if (counter != null)
                                  counter.IncrementBy(value);
                          }
                      
                          public static void SafeReset(this PerformanceCounter counter)
                          {
                              if (counter != null)
                                  counter.RawValue = 0;
                          }
                      }
                      
                      E Offline
                      E Offline
                      ekolis
                      wrote on last edited by
                      #10

                      If only you could have extension... parentheses... or whatever you'd call it... seriously, Microsoft, WHY did you have to choose null to represent an event that has no handlers?! Now instead of

                      MySpecialPropertyChanged();

                      I have to do

                      if (MySpecialPropertyChanged != null)
                      MySpecialPropertyChanged();

                      or have the program crash if nothing's listening to the event!:mad:

                      1 Reply Last reply
                      0
                      • L Lost User

                        Apparently no, isnt't it? But run this code:

                        class Program {

                        static void Main(string\[\] args) {
                            object o = null;
                        
                            Console.WriteLine(o.IsNull());
                        }
                        

                        }

                        public static class ExtensionMethods {

                        public static bool IsNull(this object obj) {
                            return (obj == null);
                        }
                        

                        }

                        If you expected it to throw a NullReferenceException (as I did), then you're in for a surprise. It actually prints true. Makes me wonder how extension methods are implemented internally. Something like a wrapper object over the null object? Any .NET experts here that can explain?

                        H Offline
                        H Offline
                        H Brydon
                        wrote on last edited by
                        #11

                        I am not a C# person, but in C++, you can call a static method through a pointer that is NULL:

                        {
                        CBlah* pBlah = NULL;
                        pBlah->SomeStaticMethod(); // legal if SomeStaticMethod() is static
                        CBlah::SomeStaticMethod(); // [same thing]
                        }

                        Calling the method requires the right access level (ie. private/protected/public) and a value may or may not be returned by the API (ie. 'void', 'int' etc.). This is not valid in java, and I don't know if it is valid in C#.

                        -- Harvey

                        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