Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing Explicit Cast in an Extension Method
    text
    copied!<p>I have a weird problem when I'm trying to cast an object via an extension method. I have a class where I wrap some functionality around an <code>IPAddress</code>.</p> <pre><code>// Dumbed down version of class public sealed class PrefixLengthIPAddress { public static explicit operator IPAddress(PrefixLengthIPAddress address) { return (address != null) ? address._address : null; } public PrefixLengthIPAddress(IPAddress address) { _address = address; _length = address.GetLength(); } private readonly ushort _length; private readonly IPAddress _address; } </code></pre> <p>I don't like the look of all the parenthesis to extract the <code>IPAddress</code> out of the object:</p> <pre><code>var family = ((IPAddress)prefixLengthAddress).AddressFamily; </code></pre> <p>I'd rather be able to do something like this:</p> <pre><code>var family = prefixLengthAddress.CastAs&lt;IPAddress&gt;().AddressFamily; </code></pre> <p>In order to do this I wrote the following Extension Method:</p> <pre><code>public static T CastAs&lt;T&gt;(this object value) where T : class { return (T)value; } </code></pre> <p>Unfortunately with this I'm getting an <code>InvalidCastException</code>:</p> <pre><code>var family = ((IPAddress)prefixLengthAddress).AddressFamily; // Works var family = prefixLengthAddress.CastAs&lt;IPAddress&gt;().AddressFamily; // InvalidCastException </code></pre> <p>I understand that in this particular case I could simply expose the <code>IPAddress</code> with a getter, but we also have more complex explicit casts that I would like to do this with.</p> <p><strong>EDIT</strong></p> <p>Thanks to Chris Sinclair's comment on using <code>dynamic</code> I have updated the extension method to look like:</p> <pre><code>public static T CastAs&lt;T&gt;(this object value) { return (T)((dynamic)value); } </code></pre> <p>There is some overhead with using <code>dynamic</code>, but it is more than fast enough for my needs. It also seems to work with all the basic type casting I've tried.</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