9

I recently saw the following code, which puzzled me.

dynamic resultObj = SomeClass.run(arg);
if (resultObj == null || resultObj.ToString() == null)
{
    /* Error handling */
}

Assuming SomeClass is your typical class (which does not override ToString()), is there a reason why the second part of the conditional would be necessary? Also, are there other potential issues with this code as it is?

Siddhartha Gandhi
  • 311
  • 1
  • 3
  • 11
  • What does `run` return? If it could possibly return a class that overrides `ToString` in a way that could return null then yes, the second check is necessary if you use the result of `ToString` in your `if` block. All `dynamic` means is "I don't know the type until runtime". – D Stanley Dec 27 '16 at 23:24
  • 1
    If it doesn't override `ToString`, then it's calling `object.ToString()` which returns [the fully qualified name of the type of the Object](https://msdn.microsoft.com/en-us/library/system.object.tostring(v=vs.110).aspx) - so yes - the `.ToString() == null` check is not required. – Rob Dec 27 '16 at 23:31
  • Seems like poor design, to allow random classes to instantiate with random returns. – Greg Dec 27 '16 at 23:35

1 Answers1

10

A dynamic can be checked for null directly, but some circumstances can cause false answers. In order to check a dynamic for null, you should cast it as an object. For example,

dynamic post = SomeMethod();
if (post.modified == null){
//could return errors.
}

in order to check this property for null, you should do something like this:

string.IsNullOrEmpty(Convert.ToString(post.Modified));

similarly, to check a dynamic for null, you should do something like this:

if ((object)post != null)

References:

https://ericlippert.com/2018/11/19/a-dynamic-definite-assignment-puzzle-part-2/

https://forums.asp.net/t/1592751.aspx?How+to+check+for+null+empty+strings+on+dynamic+objects+

So, by checking a resultObj.ToString() == null I believe this may convert the dynamic to an object and therefore enable for true null checking.

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
Patrick Knott
  • 1,666
  • 15
  • 15
  • custom operators may cause null checking on a dynamic object to return different logic than expected. https://stackoverflow.com/questions/7029699/c-how-to-perform-a-null-check-on-a-dynamic-object. You can get around this by casting to an object, I believe, feel free to downvote me and provide the reasons why I'm wrong. – Patrick Knott Nov 20 '18 at 21:34