25

A bit of an academic question, but I'm trying to understand the framework design on a deeper level.

So we have String.IsNullOrEmpty(MyString)

and we could write an extension method to enable myString.IsNullOrEmpty(), though that's arguably not the greatest idea. See: Is extending String class with IsNullOrEmpty confusing?.

So my question is, why doesn't MS write this functionality as part of the .Net framework? Is there some performance consideration? And more generally, why would any method or property viewed as valuable enough to be built as accessible via the String object not be available as a member of any object of the string type?

6
  • possible duplicate of Why is String.Format static?
    – millimoose
    Jan 7, 2013 at 13:07
  • 15
    Calling myString.IsNullOrEmpty() where myString is null would throw a NullReferenceException instead of returning true.
    – Clemens
    Jan 7, 2013 at 13:08
  • @BoltClock I understand the crux of this question is "And more generally, why would any method or property viewed as valuable enough to be build as accessible via the String object not be available as a member of any object of the string type?" - that question certainly goes over that topic.
    – millimoose
    Jan 7, 2013 at 13:10
  • @Clemens you should post that as an answer
    – lahsrah
    Jan 7, 2013 at 13:11
  • 15
    @Clemens: Unless it is an extension method. You would declare it as public static bool IsNullOrEmpty(this s) { ... }. The call s.IsNullOrEmpty() is transformed internally to IsNullOrEmpty(s) by the C# compiler. Therfore, extension methods can be called on null variables. Jan 7, 2013 at 13:22

4 Answers 4

38

The static method String.IsNullOrEmpty was introduced in the .NET Framework version 2.0. Extension methods were introduced in the .NET Framework version 3.5 together with LINQ. Therefore Microsoft did not have this option when introducing IsNullOrEmpty.

Of course, IsNullOrEmpty cannot be an instance method of String, since you cannot invoke a method on a reference which is null. However, you can invoke an extension method on such a reference, since the extension method syntax is just syntactic sugar for a static method invocation.


Let's assume that IsNullOrEmpty was an extension method. Then you could call it like this:

string s = null;
bool result = s.IsNullOrEmpty();

In a comment, someone pretends that this call would throw a NullReferenceException. The extension method would be declared like this:

public static class StringExtensions
{
    public static bool IsNullOrEmpty(this string s)
    {
        return s == null || s.Length == 0;
    }
}

... and be used like this ...

 string s = null;
 bool result = s.IsNullOrEmpty();

... which is just syntactic sugar for ...

 string s = null;
 bool result = StringExtensions.IsNullOrEmpty(s);

... and thus, would not throw an exception. Whether it is a good idea or not to do so is another question (see answer provided by usr below).

32

It is generally considered bad-practice to have an extension method not fail when invoked on a null reference. This is because just from reading the code you cannot tell that an extension method is being called. Your intuition would be to see the call ((string)null).IsNullOrEmpty() fail.

Obviously, this kind of method would not be possible as an instance method. So we are violating intuition here.

That said, I have defined exactly this extension in all important projects of mine and it is outrageously useful in a lot of cases. I am willing to accept this small level of impurity and unintuitiveness.

The framework authors obviously disagreed. I also think that this method should not go into the .NET Framework because it is kind of "advanced" and impedes learnability. A beginner might ask "Huh? Sometimes I can invoke a method on a null reference safely, sometimes I can't? How to tell when?".

8
  • 3
    Impeding learnability is a good argument as well. C# became very complex over the years. Some people tend to disapprove every solution not using LINQ or extension methods, but "classic" solutions are still good. Jan 7, 2013 at 13:41
  • 2
    This is a great answer. I chosen not to violate my intuition, and keep calling the static method as meant to be String.IsNullOrEmpty(my_variable). I only disagree on the "A beginner might ask". No, no, NO!. Not only a "beginner". Anybody can ask that question. Anybody. And if you would ask me, i would say "Anybody, and especially a polyglot programmer who had it up to here and can't stand to see any more exceptions-shortcuts to the rules that has to remember and any more variables called "result" or "tmp"." Then i would slam my keyboard. So, don't ask me.
    – Sharky
    Jul 11, 2016 at 8:47
  • 1
    So, + operator should fail too for null values for the sake of intuitiveness. Apr 22, 2017 at 13:42
  • 1
    @lockedscope you can indeed make that argument. Totally correct. But my counterargument applies as well: The hack is so convenient that it's worth it.
    – usr
    Apr 22, 2017 at 16:44
  • 1
    "Intuitive" is used in many inappropriate situations. As generally used, "intuition" is learned. I know "intuitively" that 5+4=9, but that's because I've used it so often, I didn't know by intuition that it was the case before I went to school. The same holds for driving a car - how many of us drive from point A to B and can't remember whether we stopped at all the right places and looked right and left for oncoming traffic? It's the same when we program. Lots of things come intuitively, but start on a new language or framework, and all (or most) of the intuition is gone.
    – Peter
    Apr 11, 2018 at 6:54
6

Because if you could use IsNullOrEmpty() on a null string, then you probably might want to rename the method to IsEmpty().

Jokes aside, this is how the method is implemented:

public static bool IsNullOrEmpty(string value)
{
  if (value != null)
    return value.Length == 0;
  else
    return true;
}

It's clear that the condition would always be true in case of string instances.

Also, one little detail. Take, for instance, string.Concat which is a static method. It could've been reasonable, for example, wonder why there's no relative instance method; by looking at its implementation, I believe that they wanted to make those methods as fail-proof as possible. When passing the arguments to the method, in case of null references, they are replaced with empty strings instead of having exceptions thrown. This can be useful when you don't know in advance if your string(s) will actually contain a value or be null, and I guess that the framework's developers decided that it'd be better to contribute to code readability by treating null strings as empty ones and saving the end-user an additional check. Surely, if string.Concat was an instance method (or at least had an alternative), the user could still pass null arguments, but the instance which is being operated on will necessarily be not null.

2
  • How long until somebody makes that IsEmpty()/IsNotEmpty() joke?
    – BoltClock
    Jan 7, 2013 at 13:10
  • But why is the method not in the BCL? This is the question, as I understand it.
    – usr
    Jan 7, 2013 at 13:43
0

Microsoft.IdentityModel.Tokens exposes an enumerable check of IsNullOrEmpty. In Microsoft documentation it is listed under confidential client.

Microsoft recently stated that the extension was incorrectly exposed as a public method and will be changed to internal in a later release of IdentityModel.

Conflict with Microsoft.IdentityModel.Tokens.CollectionUtilities.IsNullOrEmpty extension #1722

Below is the implementation of the exposed method:

using System.Collections.Generic;
using System.Linq;

namespace Microsoft.IdentityModel.Tokens
{
    /// <summary>
    /// A class which contains useful methods for processing collections.
    /// </summary>
    public static class CollectionUtilities
    {
        /// <summary>
        /// Checks whether <paramref name="enumerable"/> is null or empty.
        /// </summary>
        /// <typeparam name="T">The type of the <paramref name="enumerable"/>.</typeparam>
        /// <param name="enumerable">The <see cref="IEnumerable{T}"/> to be checked.</param>
        /// <returns>True if <paramref name="enumerable"/> is null or empty, false otherwise.</returns>
        public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
        {
            return enumerable == null || !enumerable.Any();
        }
    }
}

The extension can be used as follows:

string s = null;
if (s.IsNullOrEmpty())
{
    return true;
}

This passes the string as an IEnumerable<char> into the extension method for validation, therefore we can safely pass null for validation.

Borrowing from Microsoft's implementation, here is a custom extension that you can use:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace System.Collections.Generic
{
    /// <summary>
    /// A class which contains useful methods for processing collections.
    /// </summary>
    public static class IEnumerableExtensions
    {
        /// <summary>
        /// Checks whether <paramref name="enumerable"/> is <see langword="null"/> or empty.
        /// </summary>
        /// <typeparam name="T">The type of the <paramref name="enumerable"/>.</typeparam>
        /// <param name="enumerable">The <see cref="IEnumerable{T}"/> to be checked.</param>
        /// <returns><see langword="true"/> if <paramref name="enumerable"/> is <see langword="null"/> or empty, otherwise <see langword="false"/>.</returns>
        public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
        {
            return enumerable == null || !enumerable.Any();
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.