Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm working on a method that does something given a string parameter. A valid value for the string parameter is anything other than null or string.Empty. So my code looks like this.

private void SomeMethod(string someArgument)
{
    if(string.IsNullOrEmpty(someArgument))
        throw new ArgumentNullException("someArgument");

    // do some work
}

Nothing too exciting there. My question is, is it okay to throw an ArgumentNullException even if the string is equal to string.Empty? Because technically it isn't null. If you believe it should not throw ArgumentNullException, what exception should be thrown?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
369 views
Welcome To Ask or Share your Answers For Others

1 Answer

ArgumentException should be thrown for the String.Empty case. This would indicate an issue other than it being null. To avoid a NullReferenceException I check for null first, then I trim and check for the empty case to prevent any whitespace from passing.

private void SomeMethod(string someArgument)
{
    if(someArgument == null)
        throw new ArgumentNullException("someArgument");

    if (someArgument.Trim() == String.Empty)
        throw new ArgumentException("Input cannot be empty", "someArgument");

    // do some work
}

As of .NET 4.0 you can use the String.IsNullOrWhiteSpace method to perform these checks in one go. By doing so you forgo the ability to specify a granular exception type, so I would opt for the ArgumentException and update the message accordingly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...