Skip to content

Instantly share code, notes, and snippets.

@joncham
Created July 21, 2020 15:57
Show Gist options
  • Save joncham/1942f7e850b079b93cd9e88b5a0a12b8 to your computer and use it in GitHub Desktop.
Save joncham/1942f7e850b079b93cd9e88b5a0a12b8 to your computer and use it in GitHub Desktop.
Nullable Example
using System;
public class C {
public void TakeStruct<T>(T t) where T: struct
{
}
public void Test()
{
var someStruct = new SomeStruct();
SomeStruct? someStructNullable = new SomeStruct();
MyOwnNullableImpl<SomeStruct> myNullable = new SomeStruct();
TakeStruct(someStruct);
// compiler error below
TakeStruct(someStructNullable);
TakeStruct(myNullable);
}
struct SomeStruct
{
public int A;
}
struct MyOwnNullableImpl<T> where T : struct
{
public readonly bool HasValue;
public readonly T Value;
public MyOwnNullableImpl(T t)
{
HasValue = true;
Value = t;
}
public static implicit operator MyOwnNullableImpl<T>(T t) => new MyOwnNullableImpl<T>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment