Skip to content

Instantly share code, notes, and snippets.

@AvgustPol
Last active October 1, 2019 09:02
Show Gist options
  • Save AvgustPol/9c1ebfbf14365f87ac958795660b6f65 to your computer and use it in GitHub Desktop.
Save AvgustPol/9c1ebfbf14365f87ac958795660b6f65 to your computer and use it in GitHub Desktop.
Learning Null Check Operator
public class Boo
{
}
public class Foo
{
public Boo Boo { get; set; }
public List<Boo> BooList { get; set; }
}
Foo fooWithBoo = new Foo()
{
Boo = new Boo()
};
Foo fooWithNullBoo = new Foo()
{
Boo = null
};
Foo nullFoo = null;
Console.WriteLine($"booIsNotNull1 = fooWithBoo?.Boo != null; -> { fooWithBoo?.Boo != null }"); // True
Console.WriteLine($"booIsNotNull2 = fooWithNullBoo?.Boo != null; -> { fooWithNullBoo?.Boo != null }"); // False
Console.WriteLine($"booIsNotNull3 = nullFoo?.Boo != null; -> { nullFoo?.Boo != null }"); // False
Console.WriteLine($"booIsNull = nullFoo?.Boo == null; -> { nullFoo?.Boo == null }"); // True
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Foo fooWithBooList = new Foo()
{
BooList = new List<Boo>()
{
new Boo(),
new Boo(),
new Boo()
}
};
Foo fooWithoutBooList = new Foo()
{
BooList = null
};
Console.WriteLine($"fooWithBooList?.BooList.Count > 0 -> { fooWithBooList?.BooList?.Count > 0 }"); // True
Console.WriteLine($"fooWithoutBooList?.BooList.Count > 0 -> { fooWithoutBooList?.BooList?.Count > 0 }"); // False
Console.WriteLine($"fooNull?.BooList.Count > 0 -> { fooNull?.BooList?.Count > 0 }"); // False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment