C# – Implementing Nullable types in existing objects

.net-3.5cnetnullable

I am upgrading an existing application that has implemented a home-brew Constants class in its business and datalayer objects.

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:

class Constants
{
    public static int nullInt
    {
        get { return int.MinValue; }
    }
}

These constants vaules are used as defaults on almost all the object properties like this:

private decimal _unitPrice = Constants.nullInt;
public decimal UnitPrice
{
    get { return _unitPrice; }
    set { _unitPrice = (value == null) ? Constants.nullInt : value; }
}

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.

    private void Save()
    {
        //Datalayer calls and other props omitted
        SqlParameter sqlParm = new SqlParameter();
        sqlParm.Value = (this.UnitPrice == Constants.nullInt) ? DBNull.Value : (object)this.UnitPrice;

    }

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?

    public decimal? UnitPrice { get; set; }

    private void Save()
    {
        //Datalayer calls and other props omitted
        SqlParameter sqlParm = new SqlParameter();
        sqlParm.Value = this.UnitPrice ?? DBNull.Value;
    }

EDIT: 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 decimal? from decimal

Best Answer

public decimal? UnitPrice { get; set; }

private void Save()
{
    //Datalayer calls and other props omitted
    SqlParameter sqlParm = new SqlParameter();
    sqlParm.Value = this.UnitPrice ?? DBNull.Value;
}

I find this absolutely ok. This is how it is supposed to work.