1

I found this bit of code in this answer;

str.ThrowIfNullOrEmpty("str");


public static void ThrowIfNullOrEmpty(this string value, string name)
{
    if (value == null)
    {
        throw new ArgumentNullException(name);
    }
    if (value == "")
    {
        throw new ArgumentException("Argument must not be the empty string.",
                                name);
    }
}

I don't like it because (as I understand it) the parameter for an ArgumentNullException is supposed to simply be the name of the variable/parameter that was null. For this to work therefore you need the second parameter in this extension method (string name) and when you use the extension method you have to know that you are supposed to pass the name of the variable that you are checking.

There is no way to force the developer to follow this convention. Is there any way to change this method so that there is no need for the second variable (the post was from 2010 so there may be something in C# 6 for example?

EDIT

    static void Something()
    {
        string helloThere = null;
        helloThere.ThrowIfNullOrEmpty();
    }

When I call the following method I should get a ArgumentNullException with the detail being "helloThere", not "Something"

Community
  • 1
  • 1
mark_h
  • 5,233
  • 4
  • 36
  • 52

0 Answers0