Should I use Nullables or a unique value for structs?

58 Views Asked by At

I'm refactoring my program, switching from classes to structs in order to squeeze more performance out of it. I need a value or method to replace 'null' in my code. C# provides the Nullable type (i.e. StructName?), but it looks like it's more of a special class for wrapping other types rather than some sort of special null value I can trust to retain performance.

Node? temp = _closedList[_closedList.IndexOf(current)];
if (temp == null as Node) return null;
do {
    _path.Push(temp.Value);
    RecordState();
    temp = getNode(temp.Value.ParentPosition);
} while (temp.HasValue && temp.Value.Position != startNode.Position);

My other and possibly better idea is to create a special value that represents 'null', using something like Int32.MaxValue for all the relevant fields, and then a getter that checks for these special values. This sounds like it'll retain performance as far as I know, but it won't look super nice.

Node temp = _closedList[_closedList.IndexOf(current)];
if (temp.IsNull) return null;
do {
    _path.Push(temp);
    RecordState();
    temp = getNode(temp.ParentPosition);
} while (!temp.IsNull && temp.Position != startNode.Position);

I've looked at a lot of different sources around this, one said that Nullables are terrible, another said they're fine, and someone suggested unique values as a replacement. What should I do?

Note: Above code wasn't tested, I just edited to what I think a Nullable/Null Value implementation might look like.

0

There are 0 best solutions below