Skip to content

Instantly share code, notes, and snippets.

@MartinRL
Created March 28, 2012 13:47
Show Gist options
  • Select an option

  • Save MartinRL/2226310 to your computer and use it in GitHub Desktop.

Select an option

Save MartinRL/2226310 to your computer and use it in GitHub Desktop.
NotNull - plain old C# version of the exclamation mark of Spec#
public abstract class NotNullTest<TInstance> where TInstance : class
{
[Fact]
public void Given_An_Instance_When_Implicitly_Casting_To_NotNull_Then_A_NotNull_Instance_Is_Created_That_Can_Implicitly_Cast_To_Its_Type()
{
var valueInstance = CreateInstance();
NotNull<TInstance> notNull = valueInstance;
TInstance value = notNull;
Assert.Equal(valueInstance, value);
}
protected abstract TInstance CreateInstance();
[Fact]
public void Given_A_Null_NotNull_Reference_When_Implicitly_Casting_To_The_Type_Of_NotNull_Then_An_ArgumentNullException_Is_Thrown()
{
NotNull<TInstance> notNull = null;
TInstance instance;
Assert.ThrowsDelegateWithReturn implicitCast = () => instance = notNull;
Assert.Throws<ArgumentNullException>(implicitCast);
}
[Fact]
public void Given_A_Null_Reference_When_Implicitly_Casting_To_NotNull_Then_An_ArgumentNullException_Is_Thrown()
{
TInstance instance = null;
NotNull<TInstance> notNull;
Assert.ThrowsDelegateWithReturn implicitCast = () => notNull = instance;
Assert.Throws<ArgumentNullException>(implicitCast);
}
}
public class StringNotNullTest : NotNullTest<string>
{
protected override string CreateInstance()
{
return "x";
}
}
public class ClientNotNullTest : NotNullTest<MyEntity>
{
protected override MyEntity CreateInstance()
{
return new MyEntity();
}
}
public class AccountNotNullTest : NotNullTest<MyOtherEntity>
{
protected override MyOtherEntity CreateInstance()
{
return new MyOtherEntity("Donald Duck");
}
}
public class NotNull<TInstance> where TInstance : class
{
private readonly TInstance _instance;
private NotNull(TInstance instance)
{
if (instance == null)
{
throw new ArgumentNullException();
}
_instance = instance;
}
public static implicit operator NotNull<TInstance>(TInstance instance)
{
return new NotNull<TInstance>(instance);
}
public static implicit operator TInstance(NotNull<TInstance> notNull)
{
if (notNull == null)
{
throw new ArgumentNullException();
}
return notNull._instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment