Extensions with null "this" object RRS feed

  • General discussion

  • Lets say you have an Extension with the signature

    public static string Method(this string value);

    As a global rule I could see a benifit of mimicking the NullReferenceException, you should throw a ArguementNullException if value is null.

    But lets say Method is a conversion procedure, and returning null if the parameter is null maybe desirable. Would that be a bad idea?

    Additionally if your conversion is used for writing dynamic code, where "\n".Method(); returns "\"\\n\"". Would returning "null" when null.Method() is called be a good exception to the mimicking NullReferenceException rule?

    Thanks for your thoughts.
    • Changed type LitEnders Thursday, January 27, 2011 11:07 PM
    Thursday, January 27, 2011 11:06 PM

All replies

  • Personally, I think it's a bit confusing to do that, unless you have a very good reason.


    Part of the rationale for extension methods is that they are designed to look like a normal method.  If you call a normal method with null, you'll receive a NullReferenceException.

    I feel that mimicking this behavior is typically the best option, since it will keep the extension method indistinguishable from a normal method.


    There are rare exceptions, of course - but they should be rare.

    Reed Copsey, Jr. -
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    Thursday, January 27, 2011 11:25 PM
  • Note 1


    The this keyword refers to the current instance of the class. It can be used to access members from within constructors, instance methods, and instance accessors.
    Static constructors and member methods do not have a
    this pointer because they are not instantiated.
    When you are writing code in method or property of a class, using "
    this " will allow you to make use of the intellisense.
    this keyword is used when you want to track the instance, which is invoked to perform some calculation or further processing relating to that instance.


    Note 2


    There are several usages of this keyword in C#.

    1. To qualify members hidden by similar name
    2. To have an object pass itself as a parameter to other methods
    3. To have an object return itself from a method
    4. To declare indexers
    5. To declare extension methods
    6. To pass parameters between constructors
    7. To internally reassign value type (struct) value.

    You can avoid the first usage by declaring getter and setter for all fields and accessing fields only through properties. In C# 3.0 this can be done easily via automatic properties however you lose the debugging advantage of this approach.



    C# Constructor Overload (This)

    C# Naming Convention and Guidelines regarding "this" keyword




    Sunday, January 30, 2011 12:47 PM