Last active
July 28, 2020 14:23
-
-
Save guitarrapc/34b316ddcf005817fef98a8a2a00e3fe to your computer and use it in GitHub Desktop.
null conditional operator ?. for struct
This file contains 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; | |
namespace ClassLibrary1 | |
{ | |
public class Class1 | |
{ | |
private static void Main(string[] args) | |
{ | |
// enabled nullable reference type | |
A? a = new A(null); | |
a?.Name?.ToString(); | |
a?.MayBeNull()?.ToString(); // compile pass | |
a?.MayNotNull()?.ToString(); // compile pass | |
S? s = new S(null); | |
s?.DateA?.ToString(); | |
s?.MayBeNull()?.ToString(); // compile pass. | |
s?.MayNotNull()?.ToString(); // compile error. CS0023 Operator '?' cannot be applied to operand of type DateTime | |
(s?.MayNotNull())?.ToString(); // compile pass. Execute Time Error | |
} | |
} | |
public class A | |
{ | |
public string? Name { get; set; } | |
public A(string? name) => Name = name; | |
public string MayNotNull() | |
{ | |
return Name; // warning CS8603 Possible null reference return | |
} | |
public string? MayBeNull() | |
{ | |
return Name; | |
} | |
} | |
public struct S | |
{ | |
public DateTime? DateA { get; set; } | |
public S(DateTime? d) | |
{ | |
DateA = d; | |
} | |
public DateTime MayNotNull() | |
{ | |
return DateA.Value; // warning CS8629 Nullable value type may be null | |
} | |
public DateTime? MayBeNull() | |
{ | |
return DateA?.AddHours(9); | |
} | |
} | |
} |
This file contains 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
<Project Sdk="Microsoft.NET.Sdk"> | |
<PropertyGroup> | |
<TargetFramework>netcoreapp3.1</TargetFramework> | |
<OutputType>Exe</OutputType> | |
<LangVersion>8.0</LangVersion> | |
<nullable>enable</nullable> | |
</PropertyGroup> | |
</Project> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment