Managed string field null inconsistency

Managed string field null inconsistency

Old forum URL: forums.lhotka.net/forums/t/5988.aspx


JoshL posted on Saturday, December 13, 2008

Assuming a managed Name property on the Person BO, the following test passes:

Person person = Person.NewPerson();
Assert.AreEqual(string.Empty, person.Name);
person.Name = null;
Assert.IsNull(person.Name);

and this test fails:

Assert.AreEqual(string.Empty, person.Name);

Shouldn't a null person.Name be treated as String.Empty?

I would suggest that setting a property value to null should give it the same effective value as it has before any value is set into it. For strings, this would allow callers to assume that the value will never be null. I believe that this is the intent of treating a null as an empty string to begin with. So long as callers can store and retrieve a null value, code that uses the property values must deal with the possibility of a null.

If a business object developer wants to treat string.Empty as different from null, they should specify null as the default value for the property.

Thanks

RockfordLhotka replied on Saturday, December 13, 2008

There was a bug in 3.5.2 and 3.6 Beta1 where a null value was not converted to string.Empty.

Version 3.5.3 and 3.6 RTW (when it comes) resolve this issue, and any null input value for a string property is automatically converted to string.Empty. This brings the behavior in line with that for private backing fields.

If you want to preserve null string values, you'll need to override the default implementation. This should be rare however, because doing so means you can't use data binding.

JoshL replied on Saturday, December 13, 2008

Thanks, Rocky. I look forward to the updated code.

However, I'm curious why you say that the use of null strings "means you can't use data binding". I'm working in WinForms, and find that that data binding null strings has always worked just fine for me. Nullable numbers are problematic when using the Microsoft WinForms GridView, but this is easy to work around. The DevExpress grid handles nullable types by default.

That said, my preference is to be consistent with whatever approach is taken - in this case that null strings will be represented in the framework as string.Empty consistently. In Oracle, a null string and an empty string are the same anyways. For SQL Server, I'll just make sure that I convert empty strings to null when saving to the database to reduce storage and allow database check constraints and null constraints to operate.

RockfordLhotka replied on Saturday, December 13, 2008

Perhaps data binding has changed. For a very long time it has been the case
that a null string value in a property would cause Windows Forms data
binding to throw a null reference exception. This is the reason all strings
are 'de-nulled' in CSLA and all my example code.

Rocky

Copyright (c) Marimer LLC