Note that there are some explanatory texts on larger screens.

plurals
  1. POC# 4: Dynamic and Nullable<>
    text
    copied!<p>So I've got some code that passes around this anonymous object between methods:</p> <pre><code>var promo = new { Text = promo.Value, StartDate = (startDate == null) ? new Nullable&lt;DateTime&gt;() : new Nullable&lt;DateTime&gt;(DateTime.Parse(startDate.Value)), EndDate = (endDate == null) ? new Nullable&lt;DateTime&gt;() : new Nullable&lt;DateTime&gt;(DateTime.Parse(endDate.Value)) }; </code></pre> <p>Methods that receive this anonymous object type declare its type as <code>dynamic</code>:</p> <pre><code>private static bool IsPromoActive(dynamic promo) { return /* check StartDate, EndDate */ } </code></pre> <p>At run-time, however, if <code>StartDate</code> or <code>EndDate</code> are set to <code>new Nullable&lt;DateTime&gt;(DateTime.Parse(...))</code>, a method that receives this <code>dynamic</code> object (named <code>promo</code>) performs this:</p> <pre><code>if (promo.StartDate.HasValue &amp;&amp; promo.StartDate &gt; DateTime.Today || promo.EndDate.HasValue &amp;&amp; promo.EndDate &lt; DateTime.Today) { return; } </code></pre> <p>It throws an exception:</p> <pre><code>Server Error in '/' Application. 'System.DateTime' does not contain a definition for 'HasValue' </code></pre> <p>What's going on here? What don't I understand about <code>Nullable</code> types and the <code>dynamic</code> keyword?</p> <p>This code worked fine before I changed I removed the <code>struct</code> that previously stored <code>Text</code>, <code>StartDate</code>, and <code>EndDate</code> and replaced it with an anonymous type and passed it around as <code>dynamic</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload