none
which is better? RRS feed

  • Question

  •             String o = null;
    
                if (o != null)
                {
                }
    
                if (o is Object)
                {
                }
    Which is better o != null  or  o is Object
    Thursday, February 13, 2014 8:04 AM

Answers

All replies

  • Better in what way?

    I can't think of a reason why someone would ever write (o is Object) instead of (o != null). (o is Object) is just weird.

    Thursday, February 13, 2014 8:24 AM
    Moderator
  • Well better in terms of execution overhead.

    (o is Object) Should be read as .... if o is valid object ... then...

    Thursday, February 13, 2014 8:33 AM
  • "Should be read as .... if o is valid object ... then..."

    And what does "valid object" means anyway?

    o is a reference to an object. o may be null and that means that no object is referenced. Since no object is referenced this idea about a "valid" or "invalid" object doesn't make sense to begin with.

    "Well better in terms of execution overhead."

    "o != null" has less overhead compared to "o is X". It's possible that compilers will detect the "o is Object" case and change it to "o != null" so in the end both alternatives have the same performance.

    Thursday, February 13, 2014 9:03 AM
    Moderator
  • So it's better to say that if it is used like this... o is Object should be read as ... if o references an Object then....

    But since this might be converted to o != null ... it's best to use syntax here the intent is clear ... != null :)

    Thursday, February 13, 2014 9:08 AM
  • "it's best to use syntax here the intent is clear ... != null :)"

    Indeed. I've don't remember ever seeing (o is object) and I've seen a lot of code. (o is object) is certainly correct but it just isn't the norm.

    Thursday, February 13, 2014 9:18 AM
    Moderator