String Usage Guidelines

Please read this first: About Dave’s ‘unofficial’ Framework Design Guidelines.

 

ý DO NOT return a null reference (Nothing in Visual Basic and nullptr in C++/CLI) from a string property; return an empty string instead.

Users of your class expect to be able to simply check the length of a string property without also needing to check for null.

For example, in the following code, checking the length of Label.Text should never cause a NullReferenceException to be thrown:

void SetLabelTextIfNotEmpty(Label label)
{
    if (label.Text.Length == 0)
    {
        label.Text = "User name:";
    }
}

þ DO treat a null reference (Nothing in Visual Basic and nullptr in C++/CLI) and an empty string ("") as equivalent.

For example, the following method uses the default value name when passed either a null reference or an empty string.

public string GetValue(string name)
{
    if (string.IsNullOrEmpty(name))
        name = GetDefaultName();

    // Retrieve the value
    [...]
}

An exception to this guideline is when they are both considered as invalid input. In this case, distinct exceptions should be thrown to indicate that an invalid argument was passed. For example:

public void ConnectToServer(string serverName)
{
    if (serverName == null)
        throw new ArgumentNullException("serverName");

    if (serverName.Length == 0)
        throw new ArgumentException("serverName cannot be an empty string.", "serverName");
    // Connect to the server
    [...]
}
Published Monday, June 23, 2008 7:00 AM by David Kean

Comments

Monday, June 23, 2008 4:12 PM by Rory Primrose

# re: String Usage Guidelines

I agree that classes should return string.Empty rather than null, but consumers shouldn't make assumptions about the classes they call. To assume that a string isn't null is not defensive coding.

While I don't return null in my code, I will always use string.IsNullOrEmpty to check the value of a returned string just in case another dev isn't so kind. I think it is a good habit to get into.

The aim is to avoid requiring the user to have use String.IsNullOrEmpty (at least when using the built-in Framework classes. I'm also not a fan of defensive coding (which I'll elaborate in later posts) - it can hide bugs.

Tuesday, June 24, 2008 5:13 AM by Paymon

# re: String Usage Guidelines

In practice, it's better to just accept the fact that they are used interchangably. Instead make it easier and more OO style to check for "EMPTINESS" by the magic of Extension methods.

void myMethod(string arg)

{

if (arg.HasValue())

{ /* Do something, or: */}

if (arg.IsEmpty())

{ /* Do another thing */ }

}

// ...........

namespace System

public static class SystemExtensions

{

 public static bool IsEmpty(this string arg)

 {

  // ... obvious stuff here!

 }

 // ... bool HasValue(...)

}

Tuesday, June 24, 2008 11:32 AM by Steven

# re: String Usage Guidelines

@Paymon

I'm afraid I have to disagree with you. I'm not a believer of just sprinkling extension methods all over your code. The problem with extension methods is, that you can't see whether you call a static method, or you call an instance method, which can cause a NullReferenceException when the object is a null reference.

Extension methods, when used correctly can produce good readable and maintainable code and therefore I love them. When used too much in your code, you reintroduce code that is hard to maintain.

Wednesday, June 25, 2008 2:54 AM by Patrick Smacchia

# re: String Usage Guidelines

If only C# could support non-nullable types

all this artificial mess would be so much more easy to handle!

codebetter.com/.../i-want-non-nullable-types-in-c-4.aspx

Wednesday, July 09, 2008 4:39 AM by onthejazz

# re: String Usage Guidelines

I have always been a believer in returning empty strings from properties but have found problems with this technique when working with serialization.

The xml returned from a null string is different from that of an empty string, in the null string case then no element or parameter is returned, whilst an empty element or attribute is returned for an empty one.

This can be overridden with xsd defaults, but if you're working with a third party this is not always possible.

Friday, July 11, 2008 8:52 PM by Ben Voigt [C++ MVP]

# re: String Usage Guidelines

So KeyValuePair is gonna look like this now?

class KeyValuePair<TKey, TValue>

{

 public TKey Key { if (key_ == null && typeof(TKey) == typeof(string)) return (TKey)(object)string.Empty; return key_; }

...

}

And you propose breaking roundtripping?

public string s;

SomeMethod

{

 obj.StringProperty = s;

 Assert(obj.StringProperty == s); // fails

}

Wednesday, September 03, 2008 12:31 AM by Jonas

# re: String Usage Guidelines

I do not agree. using null is perfect if you want to use default values in your code.

For instance:

string name = user.FirstName ?? "n/a";

If I had used string.Empty the code would be:

string name = string.IsNullOrEmpty(user.FirstName) ? user.FirstName : "n/a"

Actually if you (or whomever owned the user class) followed the above guidelines, it would actually be:

string name = user.FirstName.Length > 0 user.FirstName : "n/a"

Regardless, you are going to have to use the above check for some properties in the Framework, such as Control.Text, so you may as well be consistent.

Leave a Comment

(required) 
(required) 
(optional)
(required)