Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Debug.Write with dynamic data?

I am doing some scripting of Adobe InDesign. Their COM implementation is really designed for VB, so it's not rigorous about reporting data types, occasionally necessitating the use of dynamics.

I'm trying to debug a chunk of code that looks like this:

foreach (dynamic pi in current.PageItems) {     if (pi is TextFrame)     {         var frame = pi as TextFrame;         var str = frame.Contents.ToString();         Debug.WriteLine(str);     } } 

This gives me a RuntimeBinderException like this:

Additional information: Cannot dynamically invoke method 'WriteLine' because it has a Conditional attribute

I get that the problem is that with Conditional attributes, the version of the code that needs to handle the type the dynamic resolves to at runtime might have gotten compiled out, but I'm explicitly converting what I want to debug to a string, so I don't see why this is still happening. How can I work around this problem?

like image 263
Tim Keating Avatar asked Dec 31 '12 18:12

Tim Keating


1 Answers

You're being bitten by your use of var here, is my guess.

I'm assuming that Contents is dynamic.

Consider this example:

dynamic d = null; var s = d.ToString(); 

s is dynamic not string.

You'll want to cast the object to object before calling ToString, or cast the result of ToString to a string. The point is that at some point, somewhere, you need a cast to get out of the dynamic cycle.

This is how I'd solve it:

string str = ((object)frame.Contents).ToString(); Debug.WriteLine(str); 

or

string str = frame.Contents.ToString() as string; Debug.WriteLine(str); 
like image 64
Servy Avatar answered Oct 11 '22 15:10

Servy