.comment-link {margin-left:.6em;}
Books & Articles I wrote.

Thursday, January 26, 2006

 

Nullable Value Types Irritation

I have to say working with these Nullable Value Types is a little irritating. Mainly because you can't go implcitly from int? to int and so although in the context of your Entity you may allow a null ID, the concept of a null ID may NOT be something you wish to expose to method calls using the object or at least avoid you having to type everything int? and then check hasValue.

Here's is what I am talking about.

You define a simple element entity as follows:

public class Element{
int? _id = null;

public int? ID
{
get { return _id;}
set {_id=value;}
}
}


You then may have a data object as follows:

public class MyData
{
public void Save(Element element)
{
if (element.ID == null)
SaveNew(...);
else
Update(...); }
}

The issue you now have is that any business methods, helper methods and so on that use this ID can then expect two types of query. The first is where you have a valid ID (number > 0) and the second is where you have a null value. Therefore, everytime you want to call a method such as the following, which will pass the ID of the element to the method you ALWAYS have to do hasValue.

public class MyBusiness
{
public void AttachToItem(int? id)
{
if (!id.hasValue)
throw new Exception("...");

//Do Something ....
}
}
Yes, before we had to do a check for -1 or some other magic number, but i'd rather there was an up front way of saying - in this certain scope it may be nullable, but outside it must have a value before it can be used as a parameter and the above method defined as follows:

public class MyBusiness
{
public void AttachToItem(int id) //i now have a valid int !
{
//Do Something ....
}
}
The only way i can think of solving this without writing loads of code, would be to have some kind of c#meta which allows you to put constraints on the variables in terms of scope, value, casting and exception.

So I may define my nullable int? as follows (making all this up now):

int? _id = null : valuecast(condition[value>0], IDException);


This basically says, define my _id variable as a nullable int? and when it is cast to an int value - [ in order to solving having to check for nulls in all my methods and so allow then to be defined as proper int value types ] - if the current value of _id is not greater than 0 then throw the user defined IDException.

Something like this would then provide me with a way of casting all of my fields for my entity throughout my entire application, which allows me to ensure that i do have a valid int (and it is NOT null) which is needed is almost all of my cases and my interfaces outside my entity can just use int's to define their interfaces.

This page is powered by Blogger. Isn't yours?

Weblog Commenting and Trackback by HaloScan.com