I've build wrapper-class intended to prevent reference types of being null, as a pre-condition code contract.
public sealed class NotNullable<T>
where T : class
{
private T t;
public static implicit operator NotNullable<T>(T otherT)
{
otherT.CheckNull("Non-Nullable type");
return new NotNullable<T> {t = otherT};
}
public static implicit operator T(NotNullable<T> other)
{
return other.t;
}
}
This works finely, but a cast is always needed like when dealing with Nullable:
public void Foo(NonNullable<Bar> bar)
{
Console.WriteLine((Bar)bar);
}
Would it be possible to have the parameter of type NonNullable behave as if it were of type T, without having to cast it? Like in Spec#:
public string Foo(Bar! bar)