开发者

Custom Structure that can be assigned Nothing and/or DBNull?

Please can any one advise me if it is possible to decalre a custom structure that can be assigned Nothing and / or Db开发者_开发问答Null.Values, and also can be instanciated as Nothing?

What I am looking to do is ceate a custom DateTime object that can recieve a DBNull.Value from a database query and also start life as Nothing. IS this possible?

Thanks in advance.

Best regards, Duane


Seems like Nullable<DateTime> (DateTime? for short, or Date? in VB.NET) gets you almost all the way there. You just need to specially deal with the conversion to/from DBNull on your own.

// You can set a DateTime? to null.
DateTime? d = null;

// You can also set it to a DateTime.
d = DateTime.Now;

// You can check whether it's null in one of two ways:
if (d == null || !d.HasValue) // (These mean the same thing.)
{ }

// Boxing a DateTime? will either result in null or a DateTime value.
SetDatabaseValue(d);

// As for conversions from DBNull, you'll have to deal with that yourself:
object value = GetDatabaseValue();
d = value is DBNull ? null : (DateTime?)value;


If you're working with DataSets, use the Field and SetField DataRow extension methods. These allow you to use Nullable types without worrying about DBNull anymore.

E.g., suppose the "MyDateField" field (of type DateTime) is nullable. Then you can do something like this:

foreach (var row in myDataTable)
{
    // will return null if the field is DbNull
    var currentValue = row.Field<DateTime?>("MyDateField");

    // will set the value to DbNull.Value
    row.SetField<DateTime?>("MyDateField", null);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜