Created
July 21, 2020 15:57
-
-
Save joncham/1942f7e850b079b93cd9e88b5a0a12b8 to your computer and use it in GitHub Desktop.
Nullable Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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