Default value and properties of type string

Default value and properties of type string

Old forum URL:

Holger posted on Wednesday, December 15, 2010


I have a CSLA managed property of type string. If I create a new instance of the class, all string properties are defaulted to string.Empty instead of null. The problem is that these values are inserted into database and all columns which are nullable have actually a value.

Is this behavior by design or is this a bug? I would expect that all string properties have a default value of null. I know that I can set the default value on RegisterProperty, but the default behavior should be null.

Best regards


public static readonly PropertyInfo<string> DescrProperty = RegisterProperty<string>(c => c.Descr, ValidationRulesFriendlyName.ArtlDescr);
public string Descr
get { return GetProperty(DescrProperty); }
   set { SetProperty(DescrProperty, value); }


JonnyBee replied on Wednesday, December 15, 2010

Nullable values can be hard to manage in databinding (and especially in Windows Forms) and would often get to be string.Empty after user has edited the field.

So the safe way is to write System.DBNull to the database if the string value IsNullOrEmpty.


ajj3085 replied on Thursday, December 16, 2010

As already stated, databinding (especially WinForms) doesn't handle null well.

In addition, unless you have a checkbox, how would your user know if the value was purposely entered as empty or if its unknown?  How do they enter "null" vs. "empty?"  Does your application care?  If not, I wouldn't worry if you have null or empty string in the database.  Maybe you should consider removing the nullablity for that column; null doesn't mean "optional," it means "unknown."

Jaans replied on Sunday, December 19, 2010

The default usage is by design - For reasons mentioned by the other posts - also Rocky discusses this in his C# Business Objects books.

Note: the SafeDataReader object will implicitly convert null values to an "equivalent" empty value.


Bruce Fincham replied on Friday, March 01, 2013

Allowing nulls on a strings means that when you are writing a SQL statement you have to check for 2 potentials empty values i.e. WHERE @Firstname IS NULL OR @Firstname = ''.

If you don't allow nulls then your SQL statements are easier to code i.e. WHERE @Firstname = ''

Copyright (c) Marimer LLC