For learning purposes, I am implementing certain code from Sedgewick & Wayne's Algorithms, Fourth Edition.
Because of language features, a direct translation doesn't seem possible.
For example, I believe the get
method in their implementation of SequentialSearchST can return null for both value and reference types because Java boxes/unboxes "value objects" (for lack of a better term) like Integer automatically.
C#, as far as I can tell, does not have an equivalent built in. It also does not appear to be possible to put an all-purpose nullable constraint on a generic type.
At least one other person has tried this, but their implementation does not allow you to store reference types for TValue
which prevents you from implementing other Algorithms classes like SeparateChainingHashST.
So, I have decided to throw a runtime error in the static constructor below. Is that about as good as it gets? That is, is there no way to throw a compile time error?
public class SequentialSearchSt<TKey, TValue>
{
private Node first;
static SequentialSearchSt()
{
if (!default(TValue).Equals(null)) throw new InvalidOperationException("TValue must be a nullable or reference type.");
}
private class Node
{
public TKey key;
public TValue val;
public Node next;
public Node(TKey key, TValue val, Node next)
{
this.key = key;
this.val = val;
this.next = next;
}
}
public TValue Get(TKey key)
{
for (Node x = first; x != null; x = x.next)
{
if (key.Equals(x.key))
{
return x.val;
}
}
return default(TValue);
}
// more code...
}