During a thought process, I came cross a dilemma between using a Nullable struct and a self-created class. The benefit of using a Nullable struct is obvious: It makes the code look pretty and save a lot of code. However, the main problem is that I need more function than Nullable here. To me, it is a crime to use a precious byte (bool) to store the fact that the object is/not a null. Two reasons here: 1. The code that I am dealing with will be stay at system engine level. Thus, any such criminal wasting of space is questionable. 2. I also need to know the fact if the object is valid or not. This means another precious byte! Keeps on giving spaces at this 8:1 ratio will render the piece into oblivion in no time.
How to address this? There are two ways here, it seems. The first one is to take the matter into my own hands and wrap a generic struct with a byte and the target primitive type in question. This can be an elegant solution but comes without the help of .NET CLR in boxing and unboxing behavior, in addition to the inelegant usage of .value all over the place. The other is to keep the fact outside of the primitive types themselves and maintain them in the declaring class. This solution is even dirtier as it brings the problem of keeping the value and flags in sync (you don't want to get a null in the flag while the value is 1, assuming 1 is a meaningful number).
The best solution would be to inherit from Nullable and be able to manipulate the byte myself. However, .NET would NOT allow you to inherit from a struct. So this is not workable.
Thus, I am trying to simulate the Nullable
in your own code.But it doesn't seem to get the same kind of treatment from the compiler. There must be more to it than just implement the implicit Nullable operator and explicit T operator.
No comments:
Post a Comment