I know what you want to do, and I've battled with it in
the past, but understand there is no perfect answer here.
Think about it; you want strong typing but you're
breaching the concept of type "int" by adding in the
concept of DBNull. A true type "int" can be many things
but it can't be DBNull.
Anyway I've used both of these approaches before:
- If you implement the property as type DataColumn you
can 'set' the property to DBNull at will. However you
must ensure that a 'set' is setting the column to an int
value and, even uglier, the user takes on the
responsibility of calling MyProperty.Value.AsInt() each
time they wish to access the property. In this approach
you gain DBNull but lose compiler enforced "int-ness".
- You could also implement the property internally as a
DataColumn field but expose the property to the world as
an int; you the implementor handle type casting. The user
would see, aka 'get' and 'set' an int property. Under
this scheme you could initialize the property to DBNull at
startup. If the user never sets the property the internal
value of the property will be DBNull. If the user sets
the property it takes on the integer value. If the
user 'gets' the property they get an integer. If the
property is DBNull during a 'get' then you can throw a
DBNull exception or return 0 {or whatever}. The only
problem with this scheme is that once the property is set
to a non-null value then the user cannot reset it to
DBNull without a helper 'reset' method or a special
integer value that signals the property implementer to set
the value to DBNull...
--Richard
-----Original Message-----
Hello,
I am trying to write a class that will expose some
properties. One of theproperty is extracted from a SQL database and can be NULL
or some integervalue.
Is there a elegant way of implementing this in C# ? I
do not want to usevariant (or similar types) because I want to retain a
strnong typesproperty. Will I have no choices but to add another
property that wouldset/get the NULL value?
Thank you!
.