Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamically coerce primitive type from one to another?
    primarykey
    data
    text
    <p>I'm working on a rather tricky problem. At the very high level, I have an object which is a primitive and I need to coerce it into a different primitive type in C#. The values <strong>and the types</strong> are determined at runtime.</p> <p>I tried roughly this (my code is more complex, this demonstrates the problem):</p> <pre><code>object value = (int)0x8ba9dc90; Type t = typeof(UInt64); object result = Convert.ChangeType(value, t); </code></pre> <p>This works some of the time, except in the case (as above) where an overflow or underflow would occur.</p> <p>What I <em>want</em> to happen is that coercion (instead of conversion) would occur. In this case, I'd simply like that "(int)0x8ba9dc90" to be "(ulong)0x8ba9dc90". Similar with floats: if value = "(float)-32.01" and "t" is "UInt64", I want the result to be "0xffffffffffffffe0". Which is exactly what you get when you run "unchecked { ulong u = (ulong)(double)-32.01; }"</p> <p>Is there any way to do this, or am I stuck writing a custom converter?</p> <p>(Yes, I realize this is an odd thing to try to do. This is all highly dynamic code, and I'm trying to do coercion in a DynamicObject.TryConvert override. I also am fully aware there are a lot of cases this will throw away data through down casts, etc. That's perfectly fine in my application. I just can't figure out how to write this without a giant nested switch statement.)</p> <p><strong>EDIT:</strong> To be clear my function looks something like this:</p> <pre><code>public override bool TryConvert(ConvertBinder binder, out object result) { if (binder.Type.IsPrimitive &amp;&amp; m_type.IsPrimitive) { // m_type is System.Type, which is m_value's current type. // m_value is System.Object, contains a primitive value. // binder.Type is the System.Type I need to coerce m_value into. result = Convert.ChangeType(m_value, binder.Type); return true; } result = null; return false; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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