Question

How do I perform a null-check on a dynamic object?

Pseudo code:

public void Main() {
    dynamic dynamicObject = 33;
    if(true) { // Arbitrary logic
        dynamicObject = null;
    }
    Method(dynamicObject);
}

public void Method(dynamic param) {
    // TODO: check if the content of 'param' is equal to null
}
Was it helpful?

Solution

Are you worried about the possibility the dynamic object will have a custom equality operator that will change the way the null is interpreted? If so just use Object.ReferenceEquals

if (Object.ReferenceEquals(null, param)) {
  .......
}

OTHER TIPS

You can always just make the param of type object, that's what the compiler is doing. When you type a parameter dynamic it just means within that method only it is using dynamic invoke for all uses of param, but outside it's just a signature of type object. A more powerful usage of your dynamicObject would be to have overloads of the method you are calling, so if you keep your example the same and just have two overloads it would call one of the two methods based on the runtime type, and you can always add more for more types.

public void Main() {
    dynamic dynamicObject = 33;
    if(true) { // Arbitrary logic
        dynamicObject = null;
    }
    Method(dynamicObject);
}
public void Method(int param) {
  //don't have to check check null
  //only called if dynamicObject is an int
}
public void Method(object param) {
// will be called if dynamicObject is not an int or null
}

You can use simplicity:

var s = data.servicePhoneNumber is null ? "" : data.servicePhoneNumber.Value;

Fast way might be:

if (_owner is null)
{

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top