What if we do like this:
First of all create one simple interface
public interface IOptional<T>: IEnumerable<T> {}
And write implementation of it
public class Maybe<T>: IOptional<T>
{
private readonly IEnumerable<T> _element;
public Maybe(T element)
: this(new T[1] { element })
{}
public Maybe()
: this(new T[0])
{}
private Maybe(T[] element)
{
_element = element;
}
public IEnumerator<T> GetEnumerator()
{
return _element.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
After this we do some changes in your Node class
public class Node<E> : IPosition<E>
{
private IOptional<E> element;
public Node<E> PrevNode { get; set; }
public Node<E> NextNode { get; set; }
//Constructor
public Node(IOptional<E> e, Node<E> p, Node<E> n)
{
element = e;
PrevNode = p;
NextNode = n;
}
}
And use it
Node<E> n = new Node<E>(
new Maybe<E>(),
null,
null
);
No more null checks inside Node class on this field
Instead of this
if (this.element != null) { .. }
Write like this
this.element.Select(e => { doSomething(e); return true; })
like this
if (this.element.Any())
{
var elem = this.element.First();
// do something
}
or write one small extension method
public static IOptional<TOutput> Match<TInput, TOutput>(
this IEnumerable<TInput> maybe,
Func<TInput, TOutput> some, Func<TOutput> nothing)
{
if (maybe.Any())
{
return new Maybe<TOutput>(
some(
maybe.First()
)
);
}
else
{
return new Maybe<TOutput>(
nothing()
);
}
}
and do like this
var result = this.element
.Match(
some: e => e.ToString(),
nothing: () => "Ups"
)
.First();