Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@guitarrapc
Last active July 28, 2020 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guitarrapc/34b316ddcf005817fef98a8a2a00e3fe to your computer and use it in GitHub Desktop.
Save guitarrapc/34b316ddcf005817fef98a8a2a00e3fe to your computer and use it in GitHub Desktop.
null conditional operator ?. for struct
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);
}
}
}
<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