Note that there are some explanatory texts on larger screens.

plurals
  1. POImplementing Nullable types in existing objects
    primarykey
    data
    text
    <p>I am upgrading an existing application that has implemented a home-brew Constants class in its business and datalayer objects. </p> <p>I want to replace this with Nullable types and do-away with the constants class, that looks like this, but with all non-nullable data types:</p> <pre><code>class Constants { public static int nullInt { get { return int.MinValue; } } } </code></pre> <p>These constants vaules are used as defaults on almost all the object properties like this:</p> <pre><code>private decimal _unitPrice = Constants.nullInt; public decimal UnitPrice { get { return _unitPrice; } set { _unitPrice = (value == null) ? Constants.nullInt : value; } } </code></pre> <p>This causes some confusion on saving object properties to the Db as all decimal's and ints have to be checked for psudo null values or else you save things like int.MinValue to the Db.</p> <pre><code> private void Save() { //Datalayer calls and other props omitted SqlParameter sqlParm = new SqlParameter(); sqlParm.Value = (this.UnitPrice == Constants.nullInt) ? DBNull.Value : (object)this.UnitPrice; } </code></pre> <p>Ok so now the question.. I want to change things around using Nullable value types as in my example below, will the change in a property from a decimal to a decimal? affect any code thats implementing these objects?</p> <pre><code> public decimal? UnitPrice { get; set; } private void Save() { //Datalayer calls and other props omitted SqlParameter sqlParm = new SqlParameter(); sqlParm.Value = this.UnitPrice ?? DBNull.Value; } </code></pre> <p><strong>EDIT:</strong> Thanks for the double check of my refactor, and yes the null check on the SET of the property in the original code would be redundant. I still want to know if code that implements this object could have any issues from the change of type to <strong>decimal?</strong> from <strong>decimal</strong></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload