-1

I want to check an objects for null be for using it in assignment statement in C#.

Consider the following C# class definitions:

class Foo
{
    public int FooId { get; set; }
    public Bar FooBar { get; set; }
}
class Bar
{
    public int BarId { get; set; }
}

Consider the following code snippet:

var foo1 = new Foo()
{
    FooId = 1,
    FooBar = new Bar()
    {
        BarId = 2
    }
};

var foo2 = new Foo()
{
    FooId = 1,
};

foo1.FooBar.BarId = foo2.FooBar == null ? foo2.FooBar.Barid : 0;

The following works fine, but seems a little outdated.

foo1.FooBar.BarId = foo2.FooBar == null ? foo2.FooBar.Barid : 0;

In C# 8 is there a different/better way to write the following using null coalescing?

JohnB
  • 3,921
  • 8
  • 49
  • 99
  • I don't know why anyone would write code like `foo2.FooBar == null ? foo2.FooBar.Barid : 0`. Best-case, you'll always get `0`. Looks like the opposite of what you actually want. – Peter Duniho Apr 24 '21 at 20:36
  • Assuming what you really meant was `foo2.FooBar != null ? foo2.FooBar.Barid : 0`, see [this answer](https://stackoverflow.com/a/38249006) in the duplicate. I.e. `foo1.FooBar.BarId = foo2.FooBar?.BarId ?? 0;`. – Peter Duniho Apr 24 '21 at 20:39

1 Answers1

-1

I believe you can use null coalescing.

int X = obj1?.prop1 ?? 0;

Unless I misunderstood the question. You can even chain these if you need, or use a nullable field and set the value later to 0 in a getter.

This even accounts for the original object possibly being null (as the ?. operator will return null too).

Richard Duerr
  • 566
  • 8
  • 24