Home > database >  Nullable operators problems in classes containing nullable objects of classes with enum fields
Nullable operators problems in classes containing nullable objects of classes with enum fields

Time:01-05

I've a problem with using ??= operator for setting a value of enum field in class that is a nullable field of other class. Simplified example below:

public class Program {
    public static void Main() {
        var en = En.val2;
        var b = new B(new A());
        b.a?.en ??= en;
    }
}

public class A {
    public En en;
    
    public A() {
        en = En.val1;
    }
}

public class B {
    public A? a;
    
    public B(A a = null) {
        this.a = a;
    }
}

public enum En {
    val1,
    val2
}

The above gives an error: "The left-hand side of an assignment must be a variable, property or indexer".

I can still do it with simply checking if b.a is null, like this:

if(b.a != null){
    b.a.en = en;
}

Is there anyway to do what I want using nullable operators?

CodePudding user response:

No, there is no way, because if b.a is null, what will you assign to it? You only specify what you assign to en, which is not sufficient information for the operation you want to do.

Anyways, the b.a?.en ??= en; operation and the piece of code below do NOT have the same meaning:

if (b.a != null) {
    b.a.en = en;
}

The null coalescing assignment translates to this:

if (b.a?.en == null) {
   b.a.en = en;
}

Which is clearly different. So I don't understand what you mean and what your code should do? So the correct answer depends on what you mean.

If you want to assign a value only if b.a is null (assign a default value), the solution would be:

if (b.a is null) {
   b.a = new A();
   b.a.en = en;
}

Or

b.a = b.a ?? new A();
b.a.en = en;

If you want to assign a value only if b.a is not null, then you should go with the if solution that you provided yourself.

CodePudding user response:

Before you try to access en in b.a, You can use ?? operator to set the default value to b.a.

static void Main(string[] args)
{
  var en = En.val2;
  var b = new B(new A());

  b.a = b.a ?? new A();
  b.a.en = en;
}

CodePudding user response:

In C#, when using ? operator means check this value, if this value is not null, it gets the value of this value's property, otherwise gets the default value of value's property default. ?? operator means that if value is null, assign the value of member at the right side of ?? operator.

But at the left side of equality, if value is null, you can't assign a value for the property before create a new instance. That's why, you should check this condition using if keyword before assignment.

For your example:

if(b.a != null){
    b.a.en = en;
}

is valid one.

b.a?.en ??= en; this is incorrect syntax. as i can see, you especially want to use a property as nullable. Imo, In this situation, the best way is control a property with if before assignment operation of en property.

  • Related